Java record-74-custom generic
Simple generic definition:
Public class GenericFoo <T> {private T foo; public void setFoo (T foo) {this. foo = foo;} public T getFoo () {return this. foo;} public static void main (String [] args) {// GenericFoo is a raw type, References to generic type GenericFoo <T> shocould be parameterized. genericFoo foo = new GenericFoo (); GenericFoo <String> sFoo = new GenericFoo <String> (); GenericFoo <Integer> iFoo = new GenericFoo <Integer> (); SFoo. setFoo ("string foo"); // sFoo. setFoo (11); // only String-type objects can be placed here. An error will be reported when 11 is compiled. IFoo. setFoo (11 );}}
2. Define two generic types and use the Generic Array:
public class GenericFoo2<T,E> { private T foo1; private E foo2; private T[] arrays; public T getFoo1() { return foo1; } public void setFoo1(T foo1) { this.foo1 = foo1; } public E getFoo2() { return foo2; } public void setFoo2(E foo2) { this.foo2 = foo2; } public T[] getArrays() { return arrays; } public void setArrays(T[] arrays) { this.arrays = arrays; } public static void main(String[] args){ GenericFoo2<String,Boolean> gf = new GenericFoo2<String,Boolean>(); gf.setFoo1("string"); gf.setFoo2(false); gf.setArrays(new String[]{"aa","bb"}); }}
3. Imitating ArrayList to implement set generics:
public class GenericCollection<E> { private Object[] array; private int index; public GenericCollection(){ this(10); } public GenericCollection(int capacity){ array = new Object[capacity]; } public void add(E e){ array[index++] = e; } public E get(int index){ return (E)array[index]; } public static void main(String[] args){ GenericCollection<Integer> gc = new GenericCollection<Integer>(); for(int i=0;i<10;i++){ gc.add(i*2); } for(int i=0;i<10;i++){ System.out.println(gc.get(i)); } }}