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

10,944

Solution 1

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");

Solution 2

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.

Share:
10,944
stackoverflow
Author by

stackoverflow

Updated on June 04, 2022

Comments

  • stackoverflow
    stackoverflow almost 2 years

    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?