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

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

/** *  Simple Version 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:

Exception in thread "main" java.lang.ClassCastException:java.lang.String cannot is cast to Java.lang.Integer at Javaba Sic.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:

package javabasic.generic; /** *  Simple Version 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");            &nBsp;     integer objint = arrlist.getobj ();         system.out.println (objint);     }}

If you want to use

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 the strong type

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

3, better implement code reuse and generic algorithm

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.