1

I can't understand the difference between the two code snippets below. Can someone help me with a simple explanation? When we should use them?

If someone can help me with a simple explanation I'll appreciate.

//1
List list1=new ArrayList();
for(Object obj:list1){}

//2
List<Object>list2=new ArrayList();
for(Object obj:list2){}

2 Answers2

1

Generics comes with Java5 and the main idea of this is to avoid the well know exception ClassCastException. In your example, before Java5 we were used to iterate collections of object and casting it's on runtime, so the exception mentioned above happened very often.

With Generics this kind of runtime exception became a compile time exception and you are be able to realized these errors early. In your example you can choice if you want to handle this situation as a runtime error (option 1) or compilation error (option 2) and realize how easier is to handle it in the option 2.

Generics is more than just implicit or explicit declaration, you should take a look at this tutorial.

0

List and List<Object> are similar (in that you can add any type to them) but different things .

List is a raw type and i can say List l =new ArrayList<Integer>() or List l =new ArrayList().

But for List<Object> ,i can only assign List implementation of Object type. I can't say List<Object> l = new ArrayList<Integer>(); .

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24