Java Containers & generics: Six, containers talk about why generics are used

Source: Internet
Author: User

Writer:bysocket (mud and brick pulp carpenter)

Weibo: Bysocket

Watercress: Bysocket

ArrayList is ubiquitous in the collection class, and generics are especially useful for collection classes. But why use generics? Understanding this problem can help to understand the more relevant points of knowledge. The masons below use the simplest examples to verify the problem.

First, the generic type

The purpose of generics is to allow more different types of objects to be reused. Yes, it's too low to understand. The real purpose is to find bugs at compile time, not at run time. (at compile time, it refers to the time when the source code is translated into machine-recognized code.) Runtime refers to the time when the code is running in the machine. Generics only exist at compile time, understanding this can help you better understand generics.

This makes it easier to find bugs and fixes at compile time than at run time.

Second, the implementation of the simple version of the ArrayList no generic type

The simple version of the arrlist has a Obejct object (because it is a, we can add any type. For example, Integer and string. The code is as follows:

?
123456789101112131415161718192021222324252627282930313233 package javaBasic.generic;/** * 简易版ArrayList */class ArrList{    private Object obj;    public Object getObj()    {        return obj;    }     public void add(Object obj)    {        this.obj = obj;    }    }public class TestArrayList{    public static void main(String[] args)    {        ArrList arrList = new ArrList();        arrList.add(1);        arrList.add("1");                Integer objInt = (Integer) arrList.getObj();        System.out.println(objInt);    }}

Running you can see that classcastexception will appear:

?
12 Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer    at javaBasic.generic.TestArrayList.main(TestArrayList.java:30)

The question to ask is: "This object property, how can not strong turn?" “

A: At compile time, the code is correct. When you run main, when you set the string type, casting the result to an integer will give you an error.

The mason's memory of the Palace came again:

1. Using generics has better security and readability than the clutter of the object code that needs to be cast.

2. Use generics to easily find and resolve bugs at compile time

Third, the use of rewriting the simple version ArrayList

Use generic code as follows:

?
123456789101112131415161718192021222324252627282930313233 package javaBasic.generic;/** * 简易版ArrayList */class ArrList<T>{    private T obj;     public T getObj()    {        return obj;    }    public void add(T obj)    {        this.obj = obj;    }    }public class TestArrayList{    public static void main(String[] args)    {        ArrList<Integer> arrList = new ArrList<>();        arrList.add(1);//      arrList.add("1");                Integer objInt = arrList.getObj();        System.out.println(objInt);    }}

If you want to use

?
1 arrList.add("1");

Will find:

This is when generics are being used, and there is no need to cast the property Get method. In fact, Java generics are just a compile-time concept, because the type will be erased after compilation, and it would have been true. Here T is the equivalent of an integer.

Iv. Summary

Mason Memory Palace :

1. Check for strong types at compile time

2, display the elimination of conversion (above the integer get omitted)

3. Better implement code reuse and generic algorithms

4. Using generics has better security and readability than the clutter of the object code that needs to be cast.

Java generics are just compile-time concepts, because the type is erased after compilation, and it's original. haha ~ next time say this.

Writer:bysocket (mud and brick pulp carpenter)

Weibo: Bysocket

Watercress: Bysocket

Java Containers & generics: Six, containers talk about why generics are used

Related Article

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.