------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------
Generic type
Benefits: 1. Transfer the classcastexception of the run-time to the compile time
Easy for programmers to solve problems and reduce run-time problems.
2. The cast is avoided.
Generic format: Defines the reference data type to manipulate by <>.
Typically used in a collection frame.
Generic class:
When a reference data type that requires an operation in a class is not deterministic,
The early use of object to achieve expansion.
Now use the generic class.
When the reference data type of the method that needs to be manipulated is indeterminate,
You can apply a generic method.
The Special place:
Static methods, which cannot be defined in a generic class.
When a static method references a type that is not deterministic, you can define the generic on the method.
Simple demonstration of generics application
ImportJava.util.*;classfanxin{ Public Static voidMain (string[] args) {TreeSet<String> ts =NewTreeset<string> (NewMycompare ());//generic types defined in <>Ts.add ("AAA");//to define a TreeSet object with a generic typeTs.add ("BBB"); Ts.add ("CCC"); Ts.add ("DDDDD"); Ts.add ("AABBB"); Ts.add ("Ad"); for(Iterator <String> it=ts.iterator (); It.hasnext ();)//generic types defined in <>{String s=It.next (); System.out.println (s); } }}classMycompareImplementsComparator<string>//generic types defined in <>{ Public intCompare (String s1,string s2) {intnum =NewInteger (S1.length ()). CompareTo (NewInteger (S2.length ())); if(num==0) returnS1.compareto (S2); Else returnnum; }}
Generic Wildcard expansion application
to qualify the upper bounds of a wildcard:
correct: vector<? extends number> x = new vector<integer> ();
error: vector<? extends number> x = new vector<string> ();
to limit the bottom bounds of a wildcard:
correct: vector<? super integer> x = new vector<number> ();
error: vector<? super integer> x = new vector<byte> ();
Tips:
qualifying wildcard characters always includes themselves.
It can only be used as a reference and cannot be used to assign values to other variables .
vector< extends number> y = new vector<integer> ();
vector<number> x = y;
The above code is wrong, and the principle is vector<object > x11 = new vector<string> ();
You can only assign a value by forcing the type conversion mode.
Comprehensive application case for generic collections
1. In the generic type? Wildcard characters
Problem: Define a method that prints out all the data in a collection of arbitrarily parameterized types, how is this method defined?
Error mode:
Public Static void printcollection (collection< object> for (Object obj:cols) { System.out.println (obj); } // Yes , New // will report an error
The right way:
public static void printcollection (collection< > cols) { for // error, because it does not know that its future match is bound to be a string Cols.size (); // Yes, this method has no relation to the type parameter }
Summary: Wildcard characters can be used to refer to various other parameterized types,? The variable defined by the wildcard is used primarily for reference, and can be called by a method that is not parameterized.
You cannot invoke methods that are related to parameterization.
2. In the generic type? The wildcard extension qualifies the upper boundary of the wildcard character:
Correct: vector<? Extends number> x = new vector<integer> ();
Error: VECTOR<? Extends number> x = new vector<string> ();
To limit the bottom bounds of a wildcard:
Correct: vector<? Super integer> x = new vector<number> ();
Error: VECTOR<? Super integer> x = new vector<byte> ();
Tip: Qualifying a wildcard always includes yourself.
Type Inference Summary
The process by which the compiler judges the actual type parameters of a generic method is called type inference, which is relative to perceptual inference, and its implementation is a very complex process.
The following rules are inferred based on the type of the parameter type or return value that was actually passed when the generic method was called:
1. When a type variable is applied to only one of the parameters and the return value in the entire argument list, it is determined by the actual application type at the time the method is called.
It is easy to infer from the sense that the type of the generic parameter is determined directly based on the parameter type or return value that is passed when the method is called, for example:
Swap (new string[3],3,4)-staticvoid swap (e[] A,int I,int j)
2. When a type variable is applied in more than one of the parameters and the return value in the entire argument list, if the method is called, the actual application type is determined by the same type.
It's easy to infer from the feeling, for example:
Add (3,5)-static <T> t Add (t a,t B)
3. When a type variable is applied to many of the parameters and return values in the entire argument list, if the method is called with a different type of actual application type,
And does not use the return value, this time take the maximum intersection type in multiple parameters, for example, the following statement actually corresponds to the type is number, compile no problem, just run the problem:
Fill (newstaticvoid Fill (t[] a,t v)
4, in a type variable in the entire parameter list of all the parameters and the return value of the multi-out is applied, if the method is called when the actual application type of the different types of the corresponding,
and using the return value, this time takes precedence over the type of the return value, for example, the following statement actually corresponds to the type of integer, the compilation will report an error, the type of the alternating variable x is changed to float,
Compare the Eclipse report error and then change the variable x type to number, without an error:
static <T> t Add (t A, T B)
5, the type inference of the parameter type has spread, the following first case infers that the actual parameter type is object, compile no problem,
In the second case, the type variable is directly determined as a string type based on the parameterized vector class instance, and the compilation will be problematic:
Copy (new integer[5],newstaticvoid copy (t[] A, T [] b), copy (new Vector<string> (),newstaticvoid copy (collection<t> a,t[] b);
Code:
Importjava.lang.reflect.InvocationTargetException;Importjava.util.ArrayList;Importjava.util.Collection; Public classGenerictest { Public Static voidMain (string[] args)throwsillegalaccessexception, IllegalArgumentException, InvocationTargetException, Nosuchmethodexception, SecurityException, exception{String s= AutoConvert ("Abad"); } //writes a generic method that automatically converts object type objects to other types. Public Static<T>T autoconvert (Object obj) {return(T) obj; } //defines a method that can populate all elements of an array of any type with an object of the appropriate type Public Static<T>voidFillarray (t[] a,t obj) { for(inti=0;i<a.length;i++) {A[i]=obj; } } //using a custom generic method, print out all the contents of a collection of arbitrary parameterized types, in which case the preceding wildcard, the scheme, is more effective than the generic method, when the same type variable is used in both of the method signatures, Or the type variable is used in the method body code and not only when it is signed, you need to use a generic method, Public Static<T>voidPrintcollection (collection<t>collections) { for(T collection:collections) {System.out.println (collection); } } //define a method in which the data in the collection of any parameter type is safely copied into an array of the appropriate type. Public Static<T>voidCopy (collection<t>collections,t[] Array) { for(T collection:collections) {System.out.println (collection); } }}
Basic data type Object wrapper class
To facilitate the manipulation of the basic data type values, the data is encapsulated into objects, the object defines the class properties, and the behavior enriches the operation of the
Because the class that describes the object is called a basic data type Object wrapper class
BYTE byte
Short Short
int Integer
Long Long
float float
Double Double
Char Character
Boolean Boolean
The wrapper object is primarily used for conversions between basic types of strings
Basic Type---> string
1. Basic type value + ""
2. valueof (base type value) with static method in string class
valueof with integer static method
1. Using static methods in the wrapper class XXX Parsexxx ("type XXX string")
long parseint ("long string")
Boolean Parseboolean ("Boolean string");
2. If the string is encapsulated by an integer object
integer i = new Integer ("123");
System.out.println (I.intvalue ())
integers have different binary embodiment:
1. Decimal---> Binary
tobinarystring (int);
2. Decimal---> Hex
tohexstring (int);
3. Decimal---> Octal
tooctalstring (int) ;
4. Other binary--->s decimal
parseint (String s , int i) [s represents the string to be converted, I represents the string's binary]
parseint ("2");
Parseiny (" 8);
parseint ("11a", +);
Note: the Equals () method in integer has been overwritten as a comparison string value
So integer a = new Integer ("3");
Integer b = new Integer (3); can be abbreviated to Integer B = 3; Automatic Boxing
SOP (A==B); False
SOP (A.equals (b); ture
A = a + 6; A = A.intvalue () + 6; Automatic unpacking
When auto-boxing loads a byte, the data is shared without re-opening the space.
Integer x = 126;
Integer y = 126;
At this time an X, y Common address sop (x==y) returns ture
Because 126 is less than one byte (128)
Code Demo
Demand:
Sort from small to large for numeric values in a string
"20 11 13-9 17 29 67 54"
Ideas:
1: The values in the string are separated by a space, so you can first use the method of the string object to split the large string into small string
2. Turn small strings into int numbers
3. Compare values and sort
ImportJava.util.*;classsortst{ Public Static voidMain (string[] args) {sortstring ("20 11 13-9 17 29 67 54"); } Public Static voidsortstring (String str) {System.out.println ("Original order:" +str); //To split a large string into an array of stringsString [] sa = Str.split (""); //creating a numeric array int[] ia =New int[Sa.length]; //to transform a string array into a numeric array for(inti = 0; i< sa.length; i++) {Ia[i]=Integer.parseint (Sa[i]); } //sort a numeric arraySystem.out.print ("After sorting:"); Arrays.sort (IA); for(intI=0;i<ia.length; i++ ) { if(i!=0) System.out.print (" "); System.out.print (Ia[i]); } }}
Operation Result:
Dark Horse programmer-generic and basic type wrapper class