Java Generics Simple Learning

Source: Internet
Author: User

I. The concept of generics (why generics are needed)?

First, let's look at the following short code:

//import java.util.List; Public classGenerictest { Public Static voidMain (string[] args) {List List=NewArrayList (); List.add (Language); List.add (Mathematical); List.add (100);//Compile Error         for(inti = 0; I < list.size (); i++) {String name= (String) list.get (i);//1System.out.println ("Name:" +name); }    }}

Defines a collection of list types, with a value of two string types added to it, followed by an integer type. This is entirely permissible because the default type of the list at this time is type object. In the subsequent loop, it is easy to get an error similar to//1 in that it has been added to the list with an integer value or other encoding reason. Because the compile phase is normal, a "java.lang.ClassCastException" exception occurs at run time. Therefore, this kind of error encoding process is not easy to find.

In the coding process as above, we found that there are two main problems:

1. When we put an object into the collection, the collection does not remember the type of the object, and when the object is removed from the collection again, the compilation type of the object is changed to the object type, but its run-time type is still its own type.

2. As a result, it is necessary to//1 the collection element into the specific target type, and the "java.lang.ClassCastException" exception can easily occur.

So is there any way that the collection can remember the types of elements within the collection and be able to achieve the "java.lang.ClassCastException" exception when the runtime does not have a problem at compile time? The answer is to use generics.

Two. What is a generic type?

Generic, which is the parameterized type. When referring to a parameter, it is most familiar to define the method when the physical parameter is called and then pass the argument when calling this method. So how do parameterized types understand? As the name implies, the type is parameterized by the original specific type, similar to the variable parameter in the method, when the type is also defined as a Parameter form (which can be called a type parameter), and then the specific type (type argument) is passed in when using/calling.

Looks a bit complicated, first we look at the above example using generic notation.

 Public Static voidMain (string[] args) {List<String> list =NewArraylist<string> ();//2List.add (Language); List.add (Mathematical); List.add (English); //List.add (+);//1 Compilation Errors//Output         for(inti=0; I<list.size (); i++) {String subjectname= List.get (i);//3System.out.println ("Account name:" +subjectname); }    }

1. Program//1 to add an integer object to the list collection, the program will not compile to report:
java.lang.Error:Unresolved compilation problem
Because the list accepts only the string object as an element, the code at//1 gets an error when compiling

2. So to use generics, create a special list collection at program 2: list, this list collection can only save string objects, cannot save other types of objects
The way to create this particular collection is to add angle brackets after the collection interface, class, and a data type in the angle brackets, which means that the collection interface, associative classes can only hold objects of a particular type
such as the type declaration at//2, it specifies that: list is not an arbitrary list, but a String type of list, writing list<string> we think list is a generic interface with a type parameter

3. The program does not require a forced type conversion at//3, because the list object can "Remember" that all its collection elements are of type string

In conjunction with the generic definition above, we know that in list<string>, String is a type argument, that is, the corresponding list interface must contain a type parameter. The return result of the Get () method is also directly the parameter type (that is, the corresponding incoming type argument).

Third, JAVA 7 generic "prism" notation

Prior to Java 7, if you were using a generic interface, class-defined variable, it would be superfluous to call the constructor to create the object when the constructor was followed by a generic type, for example:

New ArrayList<String>(); MapNew HashMap<string,integer>();

The bold code portion of the above two statements is completely redundant, which is required before Java 7 and cannot be omitted. After Java 7, just give a pair of angle brackets (<>), Java can
Infer what generic information should be in chipmunk parentheses. That is, the above two statements can be changed to the following form:

New ArrayList<>(); MapNew HashMap<>();

Thus simplifying the code:

list<string> list =NewArraylist<> ();//1List.add (Language); List.add (Mathematical); List.add (English); //List.add (+);//2//Output         for(inti=0; I<list.size (); i++) {String subjectname= List.get (i);//3System.out.println ("Account name:" +subjectname); }

Double generic type:

list<double> list =NewArraylist<> ();//2List.add (10.1); List.add (10.2); List.add (10.3); //List.add (+);//1//Output         for(inti=0; I<list.size (); i++) {Double subjectname= List.get (i);//3System.out.println ("Subject score:" +subjectname); }

Key-value pairs:

The map in Java is actually a container for storing data in the form of key-value pairs, and its commonly used implementation classes are mainly hash map
For example:
Map map = new HashMap ();
Insert element: Map.put ("key", obj);
remove element: Map.Remove ("key");
Emptying: Map.clear ();

Import Java.util.HashMap;
Import Java.util.Map;

 
map<string,double> list = new hashmap<> (); // List.put (" language ", 10.1 ); List.put ( "mathematics", 10.1 "English", 100.0 ={"language", "math", "English" // output for (int i=0; i<list.size (); I++) { Double subjectname = List.get (Arr[i]); // must be a key-value pair System.out.println ("Subject score:" +subjectname); }

Java Generics Simple Learning

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.