Java generic 1 (j2se entry 23)

Source: Internet
Author: User

Generic Type in java5.0
Very practical skills, so let's talk about it separately!
Description
This enhances Java's type security. You can check the types of objects in the container during compilation, and do not need to convert the types at runtime. Before Java se5.0, you must dynamically check and convert the objects in the container at runtime. generics are the concept of compile-time, and there is no generics at runtime.

Reduce vague containers and define the types of data to be put into containers.

List<Integer> aList = new ArrayList<Integer>();aList.add(new Integer(1));// ...Integer myInteger = aList.get(0);

A collection that supports generics can only store specified types or child types of specified types.

We can see that in this simple example, when defining alist, we specify that it is an arraylist that only accepts the integer type. When we call alist. in get (0), we no longer need to explicitly convert the result to an integer, and then assign the value to myinteger. This step is required in earlier Java versions. Maybe you are wondering, when using collection, is some type conversion all of Java generics? Far more. In this example alone, there is at least one more benefit to generics, that is, the use of generic container classes becomes more robust: earlier, the get () of the collection Interface () and the next () method of the iterator interface can only return results of the object type. We can forcibly convert this result to any object subclass without any compilation errors, however, this is obviously likely to cause serious runtime errors, because the caller determines in the Code what type of objects are retrieved from a collection, the caller may not be clear about the specific classes of objects to be put into the collection; even if the caller knows the class of the object to be put in, it cannot be guaranteed that the object to be put into the collection must be an instance of that class. Now with generics, the compiler can help us avoid similar problems as long as we specify which type of objects the collection accepts when defining. We have seen too many classcastexception in our actual work.

Usage
Declare and instantiate generic classes:
Hashmap <string, float> Hm = new hashmap <string, float> ();
The generic types of the compilation type must be consistent with those of the runtime type. No polymorphism.


The original type cannot be used.
Genlist <int> NLIST = new genlist <int> (); // compilation Error


Java SE 5.0 currently does not support the original type as the type parameter)


Define generic interfaces:
Public interface geninterface <t> {
Void func (t );
}


Define generic classes:
Public class arraylist <itemtype> {...}

Public class genmap <t, V> {...}

Example 1:

public class MyList<Element> extends LinkedList<Element>{
public void swap(int i, int j){
Element temp = this.get(i);
this.set(i, this.get(j));
this.set(j, temp);
}

public static void main(String[] args){
MyList<String> list = new MyList<String>();
list.add("hi");
list.add("andy");
System.out.println(list.get(0) + " " + list.get(1));
list.swap(0,1);
System.out.println(list.get(0) + " " + list.get(1));
}
}


Wildcard "? "
? Yes can be replaced by any type.
<?> Wildcard represents any type
<? Extends type> indicates that this type is a child type of a certain type.
<? Super type> indicates that this type is a type parent type.

1> once wildcard references are added, only elements in the original set can be accessed.
2> the basic type of the generic type can be polymorphism, and the parameter cannot be polymorphism.
3> wildcard characters can only declare one reference and cannot be instantiated, for example: List <? Extends number> list3 = new arraylist <? Extends integer> is incorrect.
4> the wildcard character can be used as a parameter to receive parameters of multiple subclasses of the same type. For example:

Public void println (? Extends number) {} in the main program, you can call the public static void main (){
Integer I = 5; long a = 6l; println (I); println ();
}

Import java. util .*;
Import static java. Lang. system. out;

Public class testtemplate {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
List <string> L1 = new arraylist <string> ();
L1.add ("ABC ");
L1.add ("def ");
List <number> L2 = new arraylist <number> ();
L2.add (1.3 );
L2.add (11 );
List <integer> l3 = new arraylist <integer> ();
L3.add (123 );
L3.add (456 );

// Print (L1 );
Print (L2 );
Print (L3 );
}

Static void print (list <? Extends number> L) {// subclass of all numbers
For (Object O: l ){
Out. println (O );
}
}

Static void print1 (list <? Super number> L) {// parent class of all numbers
For (Object O: l ){
Out. println (O );
}
}
}



"? "Can be used to replace any type, such as using wildcards to implement the print method.

Public static void print (genlist <?> List ){})

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.