• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between List l=new ArrayList(); and List<Object> l = new ArrayList<Object>();  RSS feed

 
Magesh Ramalingam
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we create arraylist by List l=new ArrayList();, it will convert all the primitives,string to object and store(i.e, it contains only objects). So why we need to mention explicitly<object>.What is the difference between these two.
 
Alex Hurtt
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need to. You don't have to use generics at all. They are totally optional and in fact are erased during compilation for purposes of backward compatibility. They exist to catch bugs at compile time rather than at run time after you have deployed your code to your customer. So go ahead and don't specify generic types. Just enjoy all your casting, class cast runtime exceptions, and not being able to use the 'for in' loop structure with anything other than Object, etc... I don't know if you ask this because you really want to know specifically in the case of Object what the point is or if you don't really get the point of generics.

The question I have for you is, if you want a collection of Strings and only Strings, then why use List<Object>? Why not use List<String>? Then the compiler will guarantee you that nobody ever puts anything in your List that is anything other than a String...The only reason I can think of offhand not to use the generics declaration is if for whatever reason you actually WANT a non-homogenous collection.
 
Campbell Ritchie
Marshal
Posts: 56520
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to JavaRanch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!