• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic List with ArrayList<String>  RSS feed

 
Chirag Sharma
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
List myList = new ArrayList<String>();

myList.add("Hi");
myList.add(12345);
myList.add(123.45);

System.out.println(myList);

I am little confuse with that, why this list can add all type of values, while we have defined that arraylist will contain only String.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're still using the raw type List. The compiler gives you a warning when you compile this. Didn't you notice the warning?

Use generics on the left hand side:
 
Chirag Sharma
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jesper,

Yea i know that we can write this like List<String>, But actually i am asking about why a raw type List allow to add different type variable in a list while i have created the object of ArrayList<String>.

List myList = new ArrayList<String>();

myList.add("Hi");// String
myList.add(12345);//int
myList.add(123.45); // double
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chirag Sharma wrote:Hi Jesper,

Yea i know that we can write this like List<String>, But actually i am asking about why a raw type List allow to add different type variable in a list while i have created the object of ArrayList<String>.

List<String> myList = new ArrayList<String>();

myList.add("Hi");// String
myList.add(12345);//int
myList.add(123.45); // double



Raw types are allowed to maintain backward compatibility with pre-generics code (and adding different types to a raw list behaves that way with pre-generics code). Also, as you noticed, if you use them, it breaks correct generics behavior. This is why you are warned by the compiler about its usage.

In summary. Don't use raw types with new code. And if you have to use them, for interoperability with legacy code, be really careful that you are using them correctly -- as generics type checking is not enforced.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!