a Java generic
JDK 4.0 The type of the collection previously loaded is ambiguous, that is, the elements in the collection, can be any type of object (the object's reference), if a
Object into a collection, it ignores its type, and it is treated as an object, thus losing its actual type. When removed from the collection, it is often necessary to turn
Low efficiency and easy to produce errors. JDK 5.0 generics refer to the requirement that a collection can hold only objects of a certain type, and that the class is performed during compilation
The collection element can also be obtained directly by the specified type.
If we only write a sorting method, we are able to sort arrays of integers, arrays of strings, and even arrays of any kind that support sorting, which is more
All right. Java generic methods and generic classes enable programmers to use a method to specify a set of related methods, or to use a class to specify a set of related types.
Java generics (generics) is a new feature introduced in JDK 5.0, which provides a compile-time type-safe detection mechanism that allows programmers to
An illegal type was detected at compile time. Using the concept of Java generics, we can write a generic method to sort an array of objects. Then, call the generic
Array of integers, floating-point arrays, string arrays, and so on.
Two generic methods
You can write a generic method that can receive different types of arguments when it is called. Depending on the type of argument passed to the generic method, the compiler applies
Each method call is processed locally.
The following is the rule that defines a generic method:
1) All generic method declarations have one type parameter declaration part (delimited by angle brackets), which is part of the type parameter declaration before the method return type (the following
<E> in the example of a polygon).
2) Each type parameter declaration part contains one or more type parameters, and the parameters are separated by commas. A generic parameter, also known as a type-variable
Is the identifier used to specify a generic type name.
3) Type parameters can be used to declare the return value type, and can be used as a generic method to get the actual parameter type placeholder.
4) The declaration of the method body of a generic method is the same as other methods. Note the type parameter can only represent a reference type and cannot be the original type (Int,double,char
, etc.).
The following example shows how to print elements of different strings using a generic method
Instance:
public class test{ //generic method PrintArray public static <E> void PrintArray (e[] inputarray) {//output array element for ( E element:inputarray) { System.out.printf ("%s", Element); } System.out.println (); } public static void Main (String args[]) { //create arrays of different types: integer,double and character integer[] Intarray = {1,2,3,4,5}; double[] Doublearray = {1.1,2.2,3.3,4.4}; Character[] Chararray = {' H ', ' E ', ' l ', ' l ', ' O '}; System.out.println ("Array Integerarray contains:");//pass an integer array printArray (intarray); System.out.println ("\narray Doublearray contains:");//pass a double-precision array printArray (Doublearray); System.out.println ("\narray Characterarray contains:");//pass a character-type array printArray (Chararray);} }
Compile the above code and run the result as follows:
Bounded type parameters
There may be times when you want to limit the range of types that are allowed to pass to a type parameter. For example, a method of manipulating numbers may only be
Accept the instance of number or number subclass. This is the purpose of the bounded type parameter. To declare a bounded type argument, first list the type parameter
The name of the number, followed by the extends keyword, immediately following its upper bound.
The following example shows how "extends" is used in the general sense of meaning "extends" (class) or "Implements" (interface). The generic method in this example returns the maximum value of three comparable objects.
Instance:
public class test{ //compares three values and returns the maximum public static <t extends comparable<t>> t maximum (t X, t y, t z) {
//assumes x is the initial maximum value T max = x; if (Y.compareto (max) >0) {//y Greater max = y; } if (Z.compareto (max) >0) {//now Z greater max = Z; } Returns the maximum object return max; } public static void Main (String args[]) {System.out.printf ("Max of%d,%d and%d are%d\n\n", 3, 4, 5,maximum (3,4,5)); System.out.printf ("Max of%.1f,%.1f and%.1f is%.1f\n\n", 6.6, 8.8, 7.7,maximum (6.6,8.8,7.7)); System.out.printf ("Max of%s,%s and%s is%s\n", "pear", "apple", "orange", Maximum ("pear", "apple", "orange"));}
Compile the above code and run the result as follows:
three-generic class the declaration of a generic class is similar to a declaration of a non-generic class except that the type parameter Declarations section is added after the class name.
As with generic methods, the type parameter declaration portion of a generic class also contains one or more type parameters, separated by commas. A generic parameter that is also
Called a type variable, is the identifier used to specify a generic type name. Because they accept one or more parameters, these classes are called parameterized
class, or parameterized type.
The following example demonstrates how we define a generic class:
Instance:
public class Box<t> { private T t; public void Add (T t) {this.t = t; } Public T get () {return t; } public static void Main (string[] args) {box<integer> Integerbox = new box<integer> (); box<string> Stringbox = new box<string> (); Integerbox.add (new Integer); Stringbox.add (New String ("Hello World")); System.out.printf ("Integer Value:%d\n\n", Integerbox.get ()); System.out.printf ("String Value:%s\n", Stringbox.get ());} }
Compile the above code and run the result as follows:
Four generics usage in the Java Collection (important)
We did not define the type of the object in the collection at the same time when we defined the collection, and we were warned at compile time, this time
We will avoid such a situation. So when we define the collection, we define the type of the objects in the collection, and the package guarantees that the object types in the collection
Sexual.
We can specify the collection when we define it, or we can specify it with iterator in the loop. Two places to designate the best. The advantage of doing this is that
The readability and stability of the program can be enhanced.
Example 1:
Import java.util.*;p ublic class test{public static void Main (string[] args) {map<string,integer> m = new hashmap< String,integer> (); M.put ("One", 1), M.put ("one", 2), M.put ("three", 3); System.out.println (M.size ()); System.out.println (M.containskey ("one")), if (M.containskey ("II")) {int i = M.get ("one"); System.out.println (i);}}}
Operation Result:
Example 2:
Import java.util.*;p ublic class test{public static void Main (string[] args) {list<string> List = new Arraylist<st Ring> (), List.add ("AAA"), List.add ("BBB"), List.add ("CCC"); for (int i=0;i<list.size (); i++) {String s = list.get (i ); System.out.println (s);} System.out.println ("-----------------"); set<myname> set = new Hashset<myname> (), Set.add (new MyName), Set.add (new MyName); Set.add (new MyName); for (iterator<myname> It=set.iterator (); It.hasnext ();) {MyName s = it.next (); System.out.println (s);}}} Class MyName implements comparable<myname>{ int age; Public MyName (int age) { this.age=age; } Public String toString () {return age+ "";} public int compareTo (MyName mn) {if (this.age>mn.age) {return 1;} else if (this.age<mn.age) {return-1;} Else{return 0;}}}
Operation Result:
Write here about the Java Collection framework of the knowledge points about this, maybe some have not been involved, but from the perspective of the javase basis, in order to
After the learning process will also involve, a deeper understanding.
Javase Getting started learning the generics of 40:java set frame