Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList Generic without Type

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 Collections can contain Collections as their elements.

The code:

public class Solution {
public static void main(String args[]) {
    ArrayList res = returnlist();
    System.out.print(res.get(0));
}
public static ArrayList<ArrayList<Integer>> returnlist() {
    ArrayList result = new ArrayList();
    ArrayList<Integer> content = new ArrayList<Integer>();
    content.add(1);
    result.add(content);
    return result;
}}

My question is

  • why can we use ArrayList result = new ArrayList(); to create an object, since we have not gave the collection the actual type of element.
  • why can we use result.add(content); to add a collection to a collection with collection "result" is just a plain collection. We have not defined it as a ArrayList of ArrayList
like image 787
Kai Avatar asked Sep 05 '14 15:09

Kai


1 Answers

Java generic collections are not stored with a type to ensure backwards compatibility with pre J2SE 5.0. Type information is removed when added to a generic collection. This is called Type Erasure.

This means that a generic collection can be assigned to a non generic reference and objects in a generic typed collection can be placed in an non generic, nontyped collection.

All Java generics really does is make sure you can't add the wrong type to a generic list and saves you from doing an explicit cast on retrieval; even though it is still done implicitly.

Further to this

  • the Java section of this answer goes a little deeper into what I just said
  • this article also covers basically what you were asking in a more complete way
  • other things to watch out for with Type Erasure
like image 69
Ross Drew Avatar answered Oct 09 '22 18:10

Ross Drew