123456789 10 1 1 12 13 14
public class generic test { public static void main(String[]args){ List List = new ArrayList(); list . add(" qqyumidi "); list . add(" corn "); list . add( 100); for(int I = 0; I< list. size (); i++){ String name =(String)list . get(I); system . out . println(" name:"+name); } }}
In this code, a list object list is defined, and two strings and a plastic data are added to it. When traversing this list to read data, we need to convert this list into a string type before we can output it (red team). Moreover, we don't know what type this list is, which causes some unnecessary troubles. Generics can solve these problems well.
Please look at the following code:
123456789 10 1 1 12 13 14 15 16
public class generic test { public static void main(String[]args){ List & lt; String & gtlist = new ArrayList & lt string & gt (); list . add(" qqyumidi "); list . add(" corn "); //list . add( 100); //There will be an error here, because it has been declared that this is a list of string type when defining the list object, so it is not allowed to be (int I = 0;; I< list. size (); i++){ String name = list . get(I); system . out . println(" name:"+name); } }}
The above code is rewritten with generics (blue code means generic writing), where
123456789 10 1 1 12 13 14 15 16 17 18 19202 12223
public class generic test { public static void main(String[]args){ Box & lt; String & gtname = new Box< String & gt (Corn); system . out . println(" name:"+name . get data()); }} Class box<T>{ Private test data; public Box(T data){ this . data = data; } public T get data(){ return data; } }
Among them, the class box is made of
In the main function, the Sting type is passed into the parameter, and at this point, the Box class is the String type.