Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
stackoverflow Avatar asked Sep 19 '25 20:09

stackoverflow


1 Answers

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");
like image 121
mojarras Avatar answered Sep 21 '25 09:09

mojarras