23rd: Please do not use the original ecological type in the code
Just like set, the generic type is explicitly written out.
24th: Eliminate non-inspected warnings
is set<string> sets = new HashSet (); this, the second generic type does not have a warning.
25th: List takes precedence over arrays
The difference between an array and a generic type:
- The array is covariant. That is, if the sub is a subtype of super, then sub[] is the subtype of super[]. Generics are immutable.
- Arrays can be materialized. Once the array is run, it knows and checks their element type constraints.
26th: Preferential consideration of generics
Class is added to the generic type.
27th: The generic method is preferred
Similar to the above, the best way to write a generic type, easy to understand other people, but also the type of restrictions and security.
Interface unaryfunction<t> { t apply (t arg);}
Public classTwentyseventh {Private StaticUnaryfunction<object> unary =NewUnaryfunction<object>() {@Override Publicobject Apply (object arg) {returnArg; } }; @SuppressWarnings ("Unchecked") Public Static<T> unaryfunction<t>identityfunction () {return(unaryfunction<t>) unary; } Public Static voidMain (string[] args) {string[] strings= {"F", "Z", "K"}; Unaryfunction<String> samestring =identityfunction (); for(String string:strings) System.out.println (samestring.apply (string)); Number[] Numbers= {1, 2.0, 3L}; Unaryfunction<Number> Samenumber =identityfunction (); for(number Number:numbers) System.out.println (samenumber.apply (number)); }}
28th: The flexibility of using the Fraiti API with restricted wildcard
Public classtwentyeighth { Public Static<E> set<e> Union (SET<?extendse> s1, set<?extendsE>S2) {Set<E> set =NewHashset<e>(S1); Set.addall (S2); returnset; } Public Static voidMain (string[] args) {Set<Integer> integers1 =NewHashset<integer> (Arrays.aslist (1, 2, 3)); Set<Integer> integers2 =NewHashset<integer> (Arrays.aslist (1, 2, 3)); Set<Double> doubles =NewHashset<double> (Arrays.aslist (1.0, 2.0, 3.0)); Union (INTEGERS1, INTEGERS2); SYSTEM.OUT.PRINTLN (Union (integers1, doubles)); }}
29th: To prioritize type-safe easy-to-buy containers
Effective Java--4 generics