Java generic code example
Java generic code example
A piece of code is better than a thousand words
Package com.apk kids. javalanguage; import java. util. arrayList; import java. util. list;/*** @ author wxb * Java generic example */public class GenericTest {// generic interface public interface MyCollection
{Public T get (int position); public T add (T t);} // The generic interface inherits the public interface MyList
Extends MyCollection
{}// Generic class public static class MyListImpl
Implements MyList
{Public T get (int position) {System. out. println ("get value at position" + position); return null;} public T add (T t) {System. out. println ("add" + t. toString (); return null ;}} // a group of public static class Fruit {} public static class Apple extends Fruit {} public static class Strawberry extends Fruit {} public static class FujiApple extends Apple {}/* ** @ param args */public static void main (String [] args) {// instantiate the generic class MyList
Strlist = new MyListImpl
(); Strlist. add ("test"); strlist. get (0); // The following Code Description: List is not List
In more general terms, the generic type has nothing to do with whether it is a child type. // List apples = new ArrayList (); // List
Fruits = apples; // used? Extends wildcard, List and List
Objects can be assigned to the List.
List apples = new ArrayList (); List
Strawberrys = new ArrayList
(); List
Fruits = apples; fruits = strawberrys; // use? Super wildcard, List
Objects can be assigned to the List
List
Fruits2 = new ArrayList
(); List
Apples2 = fruits2; // summary? Extends and? If you want to obtain data from a data type, use? Extends wildcard fruits. get (0); // The following three lines all report compilation errors // fruits. add (new Apple (); // fruits. add (new Strawberry (); // fruits. add (new Fruit (); // 2. if you want to write an object into a data structure, use? Super wildcard apples2.add (new Apple (); apples2.add (new FujiApple (); Object o = apples2.get (0); // only the Obejct Object can be obtained when retrieved. // 3. if you want to store and retrieve data, do not use wildcards. }}