ArrayList Generic without Type

后端 未结 5 1041
执念已碎
执念已碎 2020-12-03 08:32

recently I read a piece of code which seems weird to me. As we know, we need to initialize the generic type in collections when we need to use them. Also, we know Collection

5条回答
  •  渐次进展
    2020-12-03 09:00

    Just adding up to provide summarized answer

    Old way :

    (A) ArrayList result = new ArrayList();
    

    will create an Arraylist to hold "Object"


    New Way :

    ArrayList content = new ArrayList();
    

    this represents an Arraylist which will hold "Integer" objects. This was introduced for compile-time type check purposes.


    why ?

    Consider the first case. Its input type is Object. We know that Object is the super class of all classes. We can pass in an Integer object, String object and so on. When fetching the data the developer has to perform proper type casting. Say if the developer initially thinks the code will accept Integer objects so he adds the following typecast while fetching the data

    Integer integer=(Integer) content.get(0);
    

    This is supposed to work. But if mistakenly he passes a String it will result in run-time error.

    How it can be avoided ?

    By introducing compile time checks


    How it works ?

    when we specify parameterized type only Integer objects can be added to the ArrayList collection. Else it will show error.

    content.add(3); // will work
    content.add("HARSHAD"); // error shown
    

    If parameterized generic types are for type checking purposes how correct data can be retrieved from the list ?

    The compiler implicitly performs type conversion. See the sample code

    List list=new ArrayList();
    list.add(1);
    list.add(2);
    Integer integer=list.get(0);
    System.out.println(integer);
    

    What the compiler actually does when you perform compilation ?

    //perform type erasure
    (B) List list=new ArrayList();
        list.add(1);
        list.add(2);
    
    // the arraylist inturn accepts Object when you run the code 
    
    //add casting 
    Integer integer=(Integer)list.get(0);
    

    Conclusion

    If you see the codes (A) and (B) both are the same. Only difference is that in the second case the compiler implicitly does the same operation.

    Finally to answer your question ...

    ArrayList result = new ArrayList();
    

    is allowed for backward compatibility purposes. Although this is not recommended.

    Official link from Oracle docs explaining the same concept.

提交回复
热议问题