-
A simple generic definition uses:
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> should be parameterized. genericfoo foo = new genericfoo (); GenericFoo< String> sfoo = new&nBsp Genericfoo<string> (); genericfoo<integer> ifoo = new GenericFoo<Integer> (); sfoo.setfoo ("String foo");// sfoo.setfoo (one); //here can only place string type, place 11 at compile time will error. ifoo.setfoo (one); }}
2. Define two generics, and the definition of a generic array using:
public class genericfoo2<t,e> { private t foo1; private E foo2; private T[] arrays; public t getfoo1 () { return foo1; } public void setfoo1 (T &NBSP;FOO1) { this.foo1 = foo1; } public e getfoo2 () { return foo2; } public void setfoo2 (E &NBSP;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. Emulate ArrayList to implement set generics:
public class genericcollection<e> { private object[] array; private int index; Public genericcollection () { this (); } 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) {&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; 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)); } }}
Java records -74-custom generics