This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic List with ArrayList<String>  RSS feed

 
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.

 
Java Cowboy
Sheriff
Posts: 16083
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
 
author
Marshal
Posts: 23438
138
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!