stackoverflow
stackoverflow

Reputation: 19444

Java How to produce generic class that accepts a String and integer?

I'm trying to get familiar with generics in java. I'm still unsure how create a simple class to take two types (String, Integer). Below is a trivial attempt at working with generics in my contexts.

public class Container <T>
{

  public T aString()
  {
     //Do i know I have a string?
  }

  public T anInt()
  {
    //How do I know I have an integer?
  }

  public Container<T>()
  {
    //What would the constructor look like?
  }


}

I'm referencing this page oracle generics but I'm still not sure what I'm doing here. Do you first figure out what type your "T" in the class?

Is generic programming genuinely used for interfaces and abstract classes?

Upvotes: 4

Views: 15421

Answers (4)

mojarras
mojarras

Reputation: 1634

Well that Container class can actually hold a String, Integer or any type, you just have to use it correctly. Something like this:

public class Container<T> {
    private T element;

    public T getElement() {
        return element;
    }

    public void setElement(T element) {
        this.element = element;
    }

    public Container(T someElement) {
        this.element = someElement;
    }
}

And you can use it like this:

Container<Integer> myIntContainer = new Container<Integer>();
myIntContainer.setElement(234);

or...

Container<String> myStringContainer = new Container<String>();
myStringContainer.setElement("TEST");

Upvotes: 4

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

If the class does significantly different things for String and Integer, maybe it should be two classes, each specialized for one of those types.

I see generics as being useful for situations in which references of different types can be handled the same way. ArrayList<String> and ArrayList<Integer> don't need any code that is specific to String or Integer.

Upvotes: 2

Hituptony
Hituptony

Reputation: 2860

Class type = Integer.class
Integer i = verifyType("100",type);

for integer, similar with string...

reference Java Generics with Class <T>

Upvotes: 1

Philip Whitehouse
Philip Whitehouse

Reputation: 4157

If you want to use String and Integer you'll probably have to use Object as the type. This removes most of the benefit of Generics frankly and you should probably check that you actually have a sound model and reason for inter-weaving strings and integers.

But yes, it's useful for interfaces, custom classes and abstracts. It means you can guarantee the object is of the right type and removes the need to implement them each time for each type of thing.

Upvotes: 0

Related Questions