Java generic understanding (efficient java generic)

Source: Internet
Author: User
Tags addall iterable

Java generic understanding (efficient java generic)

1 * generic --> when a class or interface declaration contains one or more type parameters, it is called a generic class or interface, generic 2 * generics are more secure and expressive than the original ecological type. 3 * generics are immutable, sub extends Super (Sub extends Super, Sub [] extends Super []) 5 * (Sub extends Super, list <Sub> extends List <Super>) 6 * Check the element type information of a wildcard during compilation, discard element type information during runtime. 7 * each class is its own child type and key form parameters in the 10 * K Map of the Form Type parameter in the 9 * E set. 11 * V Map value format parameter 12 *? Any matching parameter <? Extends E>/<? Super E> 13 * limited wildcard form parameters (PECS) 14*15 * Class <T> generic 16 * Class <String> parameterized type 17 * original Class type (all generic information is deleted) 18 * Class <?> Unrestricted wildcard type 19 * Class <? Extends E> restricted wildcard type 20 * <T> Format type parameter 21 * <String> actual type parameter 22*23 * static <E> E get (E e) generic Method 24 * (<E> This is called the list of type parameters, that is, to tell the compiler before calling the method, what type is used in this method) 25 * the compiler uses the generic method to deduce the type of the type parameter list through type derivation.

 

 

Test code

1 package com. undergrowth. lang; 2 3 import java. io. serializable; 4 import java. util. arrays; 5 import java. util. collection; 6 import java. util. collections; 7 import java. util. list; 8 import java. util. concurrent. copyOnWriteArrayList; 9 10 import org. junit. test; 11 12/** 13 * generic learning Test code 14*15 * generic --> when one or more type parameters are included in the class or interface declaration, it is called a generic class/generic interface. for short, generic 16 * generic is more advantageous than the original ecological type in terms of security and presentation. 17 * generics are immutable, cannot form a covariant relationship like an array 18 * (Su B extends Super, supports Sub [] extends Super []) 19 * (Sub extends Super, does not support List <Sub> extends List <Super>) 20 * when compiling a wildcard, check its element type information, in the runtime, discard the element type information 21 * each class is its own child type and the key form parameter in the 24 * K Map of the Form Type parameter in the 22 * T form type parameter 23 * E set 25 * V Map value format parameter 26 *? Any matching parameter <? Extends E>/<? Super E> 27 * limited wildcard form parameters (PECS) 28*29 * Class <T> generic 30 * Class <String> parameterized type 31 * Class Original Ecological Type (all generic information is deleted) 32 * Class <?> Unrestricted wildcard type 33 * Class <? Extends E> restricted wildcard type 34 * <T> formal type parameter 35 * <String> actual type parameter 36*37 * static <E> E get (E e) generic Method 38 * (<E> it is called the list of type parameters, that is, to tell the compiler before calling the method, what type is used in this method) 39 * the compiler can use the generic method to derive the type 40*41 * of the type parameter list through type derivation. This content mainly involves generic and generic methods, test Case --> testGenericeClass 42 * generic set --> testGeneCollection 43 * use of limited wildcards --> testBoundWildType 44 * generic compiler maintains type information, discard during running --> testEraseGenericsInfo 45*46 * @ author Administrator 47*48 */49 public class GenericsLearn {50 51/** 52 * Test generic classes and Methods 53 */54 @ Test 55 public void testGenericeClass () {56 GenericeClass <String> gClass1 = new GenericeClass <String> ("testing generic class Parameters"); 57 System. out. println (gClass1); 58 System. out. println (gClass1.getAddSome ("generic method"); 59 System. out. println (gClass1.getAddSome (123 )); 60} 61 62/** 63 * generic test 64*65 * @ author Administrator 66*67 * @ param <T> 68 */69 private static c Lass GenericeClass <T> {70 private final T; 71 72 public GenericeClass (t T) {73 super (); 74 this. t = t; 75} 76 77/** 78 * add additional information 79*80 * @ param t 81 * @ return 82 */83 public <E> E getAddSome (E t) after obtaining the object) {84 if (t instanceof String) {85 // because the type judgment has been made when entering this method, the annotation is used to eliminate the non-Checked Warning 86 @ SuppressWarnings ("unchecked ") 87 E t1 = (E) (String. valueOf (t) + ", Additional generic protection for new messages"); 88 return t1; 89} 90 return t; 91} 9 2 93 public void iterator (Iterable <? Extends T> src) {94 for (T t: src) {95 System. out. println (t); 96} 97} 98 99 @ Override100 public String toString () {101 return "GenericeClass [t =" + t + "]"; 102} 103 104} 105 106/** 107 * testing generic set 108 */109 @ Test110 public void testGeneCollection () {111 Collection <String> collection = createCollection ("123"); 112/* 113 * for (Iterator <String> iterator = collection. iterator (); 114 * iterator. hasNext ();) {String string = (String) iterator. next (); 115 * System. out. println (string);} 116 */117 iterator (collection ); 118} 119 120/** 121 * Create A Test Set 122*123 * @ return124 */125 private <E> Collection <E> createCollection (E t) {126 // TODO Auto-generated method stub127 Collection <E> collection = Collections. emptyList (); 128 if (t instanceof String) {129 collection = new CopyOnWriteArrayList <E> (); 130 // already entered The row class type is checked, so there is no problem during the conversion. Each class is its own sub-type and super-type 131 @ SuppressWarnings ("unchecked") 132 Collection <? Extends E> initData = (Collection <? Extends E>) Arrays133. asList (new String [] {"Test Set 1", "Test Set 2", "Test Set 3"}); 134 collection. addAll (initData); 135} 136 return collection; 137} 138 139/** 140 * Create Number set 141 * this method is not recommended here only test the use of 142 * @ return143 */144 @ Deprecated145 private <E> Collection <E> createNumber () {146 Collection <E> collection = new CopyOnWriteArrayList <E> (); 147 @ SuppressWarnings ("unchecked") 148 Collection <? Extends E> initData = (Collection <? Extends E>) Arrays149. asList (new Number [] {123.2, Integer. MAX_VALUE, 789}); 150 // System. out. println (initData. getClass (). getName (); 151 collection. addAll (initData); 152 return collection; 153} 154 155/** 156 * iterative implementation of the Iterable interface 157*158 * @ param src159 */160 public <E> void iterator (Iterable <E> src) {161 for (E: src) {// The iterator is used internally to traverse element 162 System. out. println (e); 163} 164} 165 166/** 167 * tested Limited wildcard type each class is its own child type and super type 168 * PECS principle --> producer-extends, consumer-super169 */170 @ Test171 public void testBoundWildType () {172 GenericeClass <Number> gClass1 = new GenericeClass <Number> (123456); 173 System. out. println (gClass1); 174 System. out. println (gClass1.getAddSome ("123456"); 175 // create Number array 176 Collection <Number> collection = createNumber (); 177 iterator (collection ); 178 // use the GenericeClass Iteration Method for Iteration Each class is its own sub-type and super-type 179 System. out180. println ("use a limited wildcard to iterate in the form of: Iterable <? Extends T> actually: Iterable <Number extends Number> each class is its own subtype and super type "); 181 gClass1.iterator (collection); 182 Collection <Integer> collection2 = createNumber (); 183 // use foreach to iterate 184 System. out. println ("use foreach for iteration"); 185 iterator (collection2); 186 // use a limited wildcard for iteration 187 System. out188. println ("use a limited wildcard to iterate in the form of: Iterable <? Extends T> actually: Iterable <Integer extends Number> "); 189 gClass1.iterator (collection2); 190 System. out. println ("foreach iteration of String sets"); 191 Collection <String> collection3 = createNumber (); 192 iterator (collection3); 193 System. out. println ("if the collection3.add (123) method is used, the generic security check will be reflected, and the compiler will report an error"); 194 // collection3.add (123); 195 System. out196. println ("if you call the gClass1.iterator (collection3) method, there is a problem because the format is: Iterable <? Extends T> actually: Iterable <String extends Number> "); 197 // gClass1.iterator (collection3); 198 System. out. println ("Get Serializable set"); 199 Collection <Serializable> collection4 = createNumber (); 200 iterator (collection4); 201 System. out202. println ("I have been wondering, why can a Collection be returned when Collection <Number>, Collection <Integer>, Collection <String>, Collection <Serializable>, and Collection <List> are called, "203 +" because it is obvious that the createNumber method creates Is the List <Number> set of numbers. We know why generics cannot be changed. "); 204 System. out205. println ("because the generic type checks its type information in the compiler (therefore, createNumber is called when the Collection <Serializable> collection4 = createNumber (); is defined, and this method only performs type check, createNumber is a generic method, so there is no problem during compilation), and its element type information is discarded at runtime, and forced type conversion is performed at runtime, so in the (Collection <? Extends E>) Forced type conversion is actually a (Collection) List, so there is no problem during the runtime. After debugging, you will know, and I thought about it for more than an hour "); 206} 207 208/** 209 * testing generics only maintain the type information of the compiler at runtime, and do not maintain the type information of its elements. 210 * the following code reports an error in java. lang. classCastException: 211 * java. lang. double cannot be cast to java. util. list212 */213 @ Test214 public void testEraseGenericsInfo () {215 System. out. println ("Get List set"); 216 Collection <List> collection5 = createNumber (); 217 for (List list: collection5) {218 System. out. println (list. get (0); 219; 220} 221} 222 223 224 @ Test225 public void testOther () {226 Integer integer = (int) 13.2; 227 String aString = String. valueOf (13.2); 228} 229 230}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.