A little chestnut talk about Java generics basics

Source: Internet
Author: User

Background

Friday was supposed to be pleasant, but today it took a morning to check the question, why spend a morning? I summarize the reason to two points:

    • Log information is seriously lost, the vast code has no clue.
    • There is not enough knowledge of generics to cause the code to bug.

The first reason can be resolved by coding carefully after the log, we are today mainly to review the Java Generic Foundation.

A little chestnut

Let's take a look at the following example, when Test1 instantiates a list container without specifying a generic parameter, then we can put any type of object into this container, isn't that cool? But we have to be careful when we remove objects from the container, because the objects in the container have type information at run time, which means you cannot assign an object with run-time type information to another type, otherwise classcastexception.

@Testpublic void Test1 () throws Exception {    List list = new ArrayList ();    List. Add ("float.lu");    List. Add (1);    String name = (string) List. Get (0); int num = (Integer) List. Get (1); System.out. println (String.Format ("name[%s", num[%s] ", name, num));}      

The above code is OK, can compile and run well, the problem is I have to know in advance very clearly what type of object in the container is indexed to 0, what type of object is indexed to 1, it is obvious that this is impractical in practical application, it is also a very unreliable approach, then how to solve this problem? Generic type.

Introducing Generics

In order to solve this problem, we introduce generics, the following code can be seen with the above is the case of the container we add <String> this thing, the scientific name of this thing is called the generic parameter , just like the normal method with parameters, interface The E in list<e> is a formal parameter, and string is an argument.

@Testtest2() throws Exception {    list.add (list.add (1)//1}   

After introducing generics, we specify that the container can only hold objects of type string type, well, the compiler can identify generics and help us check the compilation error, the above code 1 will be compiled error. Note: generic information exists only during compilation, and the compiler can check for code violations (compilation errors) through generic information, and when the compiler compiles the code into bytecode, the generic information will no longer exist, while the object's run-time information is still there. This explains why there is a classcastexception.

Don't be happy, too early.

With generics we can get the code to compile safely, and we think he's safe, hey, is it really safe? Is it possible to say goodbye to classcastexception? The answer is: NO. Take a look at the following code:

 @Test public void Test3 () throws exception {list<string> List = new arraylist<string> (); list.add ( "a"); list.add ( "B"); list _list = list; list<integer> integerlist = _list; for (Integer item:integerlist) {System.out.println (String.Format (  "item[%s]", item)); }}

The above code compiles no problem, we do not directly assign the generic parameter to the container string of the generic parameter is an integer container, but took a little bit of attention, we now assign the list to _list,_list life to store any type, it is equivalent to no specific type, Then we assign the _list to the Integerlist container, and the Integerlist container is declared to store only objects of type integer. Sadly, this code is classcastexception when it runs, and it's clear that we know that when we iterate over the objects in the Integerlist container, they have run-time type information. When an object with string type information is assigned to an integer, it is obviously an error. It all seems to be okay, logical, but there's one problem we haven't asked: Why are there no compile errors?

Generic terminology

When we study mathematics, we tend to argue about a proof, and before argument we often have some known theorems that we don't need to prove, and the following "theorems" will be used to directly answer the questions left in the previous section.

    • List<e> is called a generic type.
    • The E in list<e> is called a type variable or a type parameter.
    • List<string> is called a parameterized type.
    • A String in list<string> is called the actual type parameter.
    • List<e> in the <> year typeof.
    • List is called the original type.
    • A parameterized type can reference a primitive type object and compile a report warning.
    • The original type can reference a parameterized type object and compile a report warning.

,list<integer> integerlist = _list can be compiled by the above.

See the Essence

After some minor twists and turns, we understand some of the nature of generics: Generics are used by the Javac compiler, Javac is a Java compiler, and generics allow code to determine type safety during compilation, such as when we tell the compiler that a container can only store objects of a certain type. Then the compiler will check for us, ensure type safety, but security is relative, as long as we escape the compiler, we have 100 ways to let the code classcastexception (such as reflection). At the same time, the parameterized type does not have any generic information at run time, which is why List.class and List<string>.class are the same thing. In addition to parameterized types, objects in a container have type information when they run, which is why they are classcastexcetion. There is a lot of content about generics, here do not say much, the text of the mistake also welcome message discussion.

A little chestnut talk about Java generics basics

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.