Java Generics detailed 1__java

Source: Internet
Author: User

This article is from: Java head http://mp.weixin.qq.com/s/PIBZQDFQLk3aTX11x5-NNw


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

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

Defines a collection of list types, in which two string-type values are added, followed by a value of an integer type. This is entirely permissible because the list default type is type Object. In subsequent loops, it is easy to have errors similar to those in//1 because you have added an integer value or other encoding reason to the list before you forget it. Because the compile phase is normal, a "Java.lang.ClassCastException" exception appears at run time. As a result, this type of error encoding 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 this object, and when this object is fetched again from the collection, the modified object's compilation type becomes type Object, but its run-time type is still its own type.

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

So is there any way to make the collection can remember the types of elements in the collection, and can achieve as long as the compile without problems, the runtime will not appear "Java.lang.ClassCastException" exception. The answer is to use generics.

Two. What is generics.

Generics, or "parameterized type." When referring to a parameter, the most familiar is the physical parameter when the method is defined, and then the argument is passed when this method is called. So how do parametric types understand? As the name suggests, the type is parameterized by the original specific type, similar to the variable parameter in the method, where the type is defined as a parameter form (which can be called a type parameter) and then passed into the specific type (the type argument) at the time of use/invocation.

Looks like a bit complicated, first of all, let's take a look at the example above using the generic type.

When a generic type is written, a compile error occurs when//1 wants to join an integer object, and by List<string>, the list can be directly qualified to contain only String elements, thereby eliminating the need for coercion of type conversions at//2, because at this point , the collection remembers the type information of the element, and the compiler has been able to confirm that it is a string type.

In conjunction with the above generic definition, 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). Here's a look at the specific definition of the list interface:

 1 public Interface list<e> extends collection<e> {2 3 int size ();
 4 5 Boolean isempty ();
 6 7 Boolean contains (Object O);
8 9 iterator<e> iterator ();
Object[] ToArray ();
<T> t[] ToArray (t[] a);
Boolean add (E);
Boolean remove (Object O);
Boolean containsall (collection<?> c);
Boolean AddAll (collection< extends e> c);
Boolean addall (int index, COLLECTION&LT;? extends e> c);
Boolean RemoveAll (collection<?> c);
Boolean retainall (collection<?> c);
void Clear ();
Boolean equals (Object O);
hashcode Int ();
E get (int index);
e-Set (int index, e element);
(int index, E element);
E-Remove (int index);
indexOf int (Object o);
LastIndexOf int (Object o);
Listiterator<e> Listiterator (); Listiterator<e> listiterator (int index);
list<e> sublist (int fromindex, int toindex); 52}

We can see that in the list interface, after the generic definition is adopted, the E in,<e> represents the type parameter, can receive the concrete type argument, and in this interface definition, wherever e appears, it represents the same type argument accepted from outside.

Naturally, ArrayList as the implementation class of the list interface, which is defined in the form of:

Thus, we understand from the source code point of view why//1 Add an integer type Object compilation error, and//2 Place get () to type directly is string type.

Three. Custom generic interfaces, generic classes, and generic methods

From the above, we have already understood the specific operation process of generics. Also know that interfaces, classes, and methods can also be defined using generics, as well as the corresponding use. Yes, when used specifically, it can be divided into generic interfaces, generic classes, and generic methods.

Custom generic interfaces, generic classes, and generic methods are similar to the list and ArrayList in the Java source code above. As follows, let's look at one of the simplest generic classes and method definitions:

In the definition of generic interfaces, generic classes, and generic methods, our common parameters, such as T, E, K, V, are often used to represent generic parameters, as they are received from type arguments passed in from outside use. Then for different incoming type arguments, the type of the corresponding object instance generated is the same.

public class generictest{

public static void Main (string[] args) {

box<string> name = new Box<string> ("corn");
box<integer> age = new box<integer> (712);

System.out.println ("Name class:" + Name.getclass);//com.qqyumidi.box

System.out.println ("Age class:" + Name.getclass);//com.qqyumidi.box

System.out.println (Name.getclass = = Age.getclass ());//true

}

}

As a result, we found that when using generic classes, although a different generic argument is passed in, there is no real sense of generating different types, and a generic class passed in different generic arguments has only one memory, or the original most basic type (box in this case), of course, Logically we can understand several different generic types.

The reason is that the concept of generics in Java is proposed to causes it to only function in the code compilation phase, during compilation, for the correct validation of generic results, the generic information will be wiped out, that is, after the successful compilation of the class file does not contain any generic information. Generic information does not enter the Run-time phase.

To sum it up, a generic type is logically viewed as a number of different types, and is actually the same basic type.

Four. Type wildcard characters

The above conclusion, we know that,box<number> and box<integer> are actually Box types, now need to continue to explore a problem, then logically, similar to box<number> and box< Integer> can be considered as a generic type with a parent-child relationship.

To figure this out, let's continue to look at the following example:

public class generictest{
public static void Main (string[] args) {
box<number> name = new box<number> (99);
box<integer> age = new box<integer> (712);


GetData (name);


The method GetData (box<number>) in the type generictest is
Not applicable for the arguments (box<integer>)
GetData (age); 1


}
public static void GetData (box<number> data) {
SYSTEM.OUT.PRINTLN ("Data:" + data.getdata ());
}
}

We found that there was an error message at the code//1: The Method GetData (box<number>) in the T ype Generictest was not applicable for the arguments ( box<integer>). Obviously, by prompting the information, we know that box<number> is not logically considered a box<integer> parent class. So, why.


1 public class Generictest {

2

3 public static void main (string[] args) {

4

5 box<integer> A = new box<integer> (712);

6 box<number> B = A; 1

7 box<float> f = new box<float> (3.14f);

8 B.setdata (f); 2

9

10}

11

The public static void GetData (box<number> data) {

SYSTEM.OUT.PRINTLN ("Data:" + data.getdata ());

14}

15

16}

17

Class Box<t> {

19

Private T data;

21st

Public Box () {

23

24}

25

Num public Box (T data) {

SetData (data);

28}

29

Public T GetData () {

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.