-2

For example look at this:

ArrayList<String> arrayList = new ArrayList<String>();

Could I use the <>s with a custom class? How do I use them?

Rytmis
  • 31,467
  • 8
  • 60
  • 69
user2223779
  • 47
  • 1
  • 3

2 Answers2

3

You can put any class in the <> as long as it fulfills the generic class's constraints:

ArrayList<MyClass> arrayList = new ArrayList<MyClass>();

You can define your own class to use the <> simply:

class MyGenericClass<E> {
    E e;
    MyGenericClass(E e) { this.e = e; }

    E getE() { return e; }
    void setE(E e) { this.e = e; }
}

Now you can make your own:

MyGenericClass<String> stuff = new MyGenericClass<String>("Foo");
System.out.println(stuff.getE());
nneonneo
  • 171,345
  • 36
  • 312
  • 383
2

The tutorial Generics gives you all the information needed. The section Generic types shows how to declare and implement custom classes.

class MyClass<T> {
    ...
}
Howard
  • 38,639
  • 9
  • 64
  • 83