1 /*2 * A. Benefits of generics3 * Improved security (converting run-time errors to compile time)4 * eliminates the hassle of forcing type conversions5 * b. Generic basic use6 * The <> must be a reference data type7 * C. Considerations for generic use8 * Before and after generics must be consistent, or the following generics can be omitted without writing (1.7 new feature diamond generics)9 */Ten Public Static voidMain (string[] args) { One Aarraylist<person> list =NewArraylist<person>(); -List.add (NewPerson ("Zhang San", 19)); -List.add (NewPerson ("John Doe", 20)); theIterator<person> it =list.iterator (); - while(It.hasnext ()) { -Person p =It.next (); -System.out.println (P.getname () + "..." + p.getage ());//Zhang Three ... 19 Li Si ... - + - //System.out.println (It.next (). GetName () + "..." + it.next (). Getage ()); + //Zhang Three ... 20 when using the next () method, it is important to note that the property or method cannot be called directly with It.next (), only one time next () method can be called, otherwise it will result in data dislocation A } at } - - /////////////////////////////////////////////////////////////////////// - - Public classDemo3_generic { - in Public Static voidMain (string[] args) { - to } + - } the * InterfaceInter<t>{ $ Public voidShow (T t);Panax Notoginseng - } the + classDeomImplementsInter<string>{ A //The first implementation class plus generics, it is recommended to use this method the @Override + Public voidShow (String t) { - System.out.println (t); $ } $ - } - the classDemo2<t>ImplementsInter<t>{ - //The second implementation class is generic because there is no need to add generics on the classWuyi @Override the Public voidShow (T t) { - System.out.println (t); Wu } - About } $ - //////////////////////////////////////////////////////////////////////////// - - Public classDemo4_generic { A + /* the * A: Generic wildcard characters <?> - * Any type, if not explicitly, then object and any Java class $ * B:? extends E the * down qualification, E and its subclasses the * C:? Super E the * up limit, E and its parent class the */ - Public Static voidMain (string[] args) { in the //list<?> List = new arraylist<string> (); theArraylist<person> List1 =NewArraylist<>(); AboutList1.add (NewPerson ("Zhang San", 23)); theList1.add (NewPerson ("John Doe", 24)); the theArraylist<worker> List2 =NewArraylist<>(); +List2.add (NewWorker ("Harry", 25)); - the List1.addall (list2);Bayi the System.out.println (list1); the - } - the } the the /////////////////////////////////////////////////////////////////
Generics of Java