Java Generic code example
A piece of code is worth thousands of thousand
Package Com.apkkids.javalanguage;import Java.util.arraylist;import Java.util.List;/** * @author WXB * Java Generic example */ Public class generictest { //generic interface Public interface mycollection<T>{ PublicT get (int position); PublicT Add (t T); }//generic interface inheritance Public interface MyList<t> extends mycollection<t> {}//Generic class Public Static class Mylistimpl<t> implements MyList<t >{ PublicT get (int position) {System.out.println ("Get value at position"+ position);return NULL; } PublicT Add (T t) {SYSTEM.OUT.PRINTLN ("Add"+t.tostring ());return NULL; } }//A set of classes to be used 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 Staticvoid Main (string[] args) {//Instantiate generic classMylist<string> strlist =NewMylistimpl<string> (); Strlist.add ("Test"); Strlist.get (0);The following code shows that:list<apple> is not a subclass of list<fruit>, and in more general words, the generic type has no relation to whether it is a subtype. //list<apple> apples = new arraylist<apple> ();//list<fruit> fruits = apples; //Use the extends wildcard,list<apple> and list<strawberry> objects can be assigned to LIST<? extends fruit> List<Apple> apples =NewArraylist<apple> ();List<Strawberry> Strawberrys =NewArraylist<strawberry> ();List<?Extends fruit> fruits = apples; Fruits = Strawberrys;//Use the? Super Wildcard,list<fruit> object can be assigned to LIST<? Super Apple> List<Fruit> fruits2 =NewArraylist<fruit> ();List<?Super apple> apples2 = fruits2;//Summary of the characteristics of the extends and the super wildcard, we can draw the following conclusions://1. If you want to get data from a data type, use the? Extends wildcard characterFruits.get (0);//The following three lines will compile the error//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 the? Super wildcard characterApples2.add (NewApple ()); Apples2.add (NewFujiapple ()); Object o = Apples2.get (0);only OBEJCT objects are available when//removed//3. If you want to save and take it, do not use wildcard characters. }}
Java Generic code example