[New Features of Java 5] generic

Source: Internet
Author: User

[New Features of Java 5] generic
Java Integration

The collection in Java has a disadvantage: When we place data in the collection, the collection will not remember the data type. That is to say, when we get data from the collection, the Data Type changes to the Object type.

In other words, the set has no restrictions on the element type. This may cause some problems. For example, if we want to create a List set that stores strings specially, we can also place the Integer data. Even if string data is put in, type conversion is still required when retrieving from the List set (because the element types in the set are all Object types ).

For example, the following example creates a List set that only saves strings, but Integer numbers can also be saved. When retrieving elements from the List set, the type conversion is required.

Public class Demo {public static void main (String [] args) {// create a List set that only saves strings List = new ArrayList (); list. add (Hello); list. add (World); list. add (1000); for (int I = 0; I <list. size (); I ++) {String str = (String) list. get (I); System. out. println (str );}}}

To solve this problem, we can customize the extended ArrayList to ensure that the custom ArrayList can only store string data types.

Public class Demo {private List list = new ArrayList (); // defines the add method of the custom ArrayList public boolean add (String ele) {return list. add (ele);} // rewrite the get method and change the type of the get Method to the String type. public String get (int index) {return (String) list. get (index);} public int size () {return list. size ();}}

Although this method is effective, it has many limitations. In actual development, we need to customize a large number of List sub-classes to increase the development workload, and it is not universal.

What is generic

After Java 5, we provide generics to solve the above problems. First, let's view the source code snippets of the following ArrayList:

public class ArrayList
  
    {    public int size() {        return size;    }    public boolean add(E e) {        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }    public E get(int index) {        rangeCheck(index);        return elementData(index);    }}
  

By viewing the source code, we found that in the ArrayList underlying code, the ArrayList class is followed by "", which is actually a generic type. In the add method and get method of the ArrayList class, we can also see that the element type added by the add method is E, and the type returned by the get method is E.

Therefore, the above problems can be solved using the generics provided after Java 5:

Public class Demo {public static void main (String [] args) {// create a List set that only saves strings
  
   
List = new ArrayList
   
    
(); List. add (Hello); list. add (World); for (int I = 0; I <list. size (); I ++) {String str = (String) list. get (I); System. out. println (str );}}}
   
  

So what is generic? Generic parameters allow you to specify a type parameter when defining a class or interface. This type parameter will be determined when declaring a variable or creating an object. To put it bluntly, if the set is like a bottle filled with stuff, then the generic type is like a label on the bottle, specifying which type of stuff the bottle can only store.

How to define generic classes

What is the specific method for defining interfaces or classes using generics? In fact, in the above case, the ArrayList class we are viewing is a generic class, and the List implemented by the ArrayList class is a generic interface.

public class ArrayList
  
    {    public int size() {        return size;    }    public boolean add(E e) {        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }    public E get(int index) {        rangeCheck(index);        return elementData(index);    }}
  
public interface List
  
    {    int size();    boolean add(E e);    E get(int index);}
  

Through the above two cases at the bottom layer of Java, what rules should we follow if we customize generic interfaces or classes?

Write "" after the class name to indicate that the class receives the generic type, and T indicates the generic type. Specify the specific type when creating this type of object. (T does not have the actual meaning. You can specify it here .) Methods in generic classes can receive generic parameters or return generics. In a generic class, the generic type can only be used in non-static members.
public class Demo
  
    {    private T bean;    public T getBean() {        return bean;    }    public void setBean(T bean) {        this.bean = bean;    }}
  
How to define generic methods

In addition to defining generic interfaces or classes, you can also customize the type parameters when defining interfaces or classes. Java 5 and later versions also provide support for generic methods.

A generic method defines one or more type parameters when declaring a method. The usage format of generic methods is as follows:

Modifier
  
   
Return Value Type method name (parameter list) {method body}
  

According to this format, we customize a generic method:

Public class Demo {public static
  
   
T get (T [] ts) {return ts [0];} public static void main (String [] args) {Integer [] arr = new Integer [] {1, 2, 3}; // automatically identifies generics when calling methods! Because the arr parameter is Integer [], it is equivalent to assigning the value of T to Integer I = get (arr); System. out. println (I );}}
  
Type wildcard

If we use a generic class, we should pass in a type real parameter for this generic class. If we do not pass the type real parameter, it will cause a generic security warning. Here is an example:

public class Demo {    public void demo(List
  
    list) {        for (int i = 0; i < list.size(); i++) {            System.out.println(list.get(i));        }    }}
  

In this case, we define a method to receive a String-type List set, traverse the List set, and print the content of each element. However, the problem is that this method can only traverse the List set with the print generic String type. To achieve the same function of Integer type, we need to redefine a method.

public class Demo {    public void demo(List
  
    list) {        for (int i = 0; i < list.size(); i++) {            System.out.println(list.get(i));        }    }}
  

But the problem is that when the above two methods appear in the same class, an error is reported."Method demo (List) has the same erasure demo (List) as another method in type Demo". The reason is that, apart from the differences in generics, these two methods are actually the same, and multiple identical methods are not allowed in the same class.

The solution to this problem is to remove the generic content in the parameters, for example, the following code:

public class Demo {    public static void print(List list) {        for (int i = 0; i < list.size(); i++) {            System.out.println(list.get(i));        }    }    public static void main(String[] args) {        List
  
    strings = null;        List
   
     integers = null;        print(strings);        print(integers);    }}
   
  

In this way, the print method can receive both the List set of Integer type and the List set of String type. However, a wildcard Security Warning is prompted."List is a raw type. References to generic type List shocould be parameterized".

To completely solve this problem, we need to use the type wildcard. The code above can be rewritten as follows through the type wildcard:

public class Demo6 {    public static void print(List
   list) {        for (int i = 0; i < list.size(); i++) {            System.out.println(list.get(i));        }    }    public static void main(String[] args) {        List
  
    strings = null;        List
   
     integers = null;        print(strings);        print(integers);    }}
   
  

In the above case,

List
   list         ①List
   list          ②

Here, ① indicates the upper boundary of the type wildcard, meaning that the current generic type can receive the subtypes of all Number types; ② indicates the lower boundary of the type wildcard, it indicates that the current generic type can receive all Integer type parent types.

 

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.