4

I'm having trouble understanding why the java-compiler allows non-specific collections to be assigned collections where the variable have been specified. Like this:

    ArrayList list = new ArrayList();
    // Operations on list
    ArrayList<String> stringList = list;

There's potential for all kinds of casting errors in this, it seems to me it would make more sense if the compiler stopped you from doing this in the first place.

I'm only asking because I'm curious of this somewhat weird aspect of the language, I don't actually have trouble getting the code to work (although I might some day when I need to use an ArrayList with all kinds of classes in it).

  • possible duplicate of [Converting non-generic List type to Generic List type in Java 1.5](http://stackoverflow.com/questions/1498963/converting-non-generic-list-type-to-generic-list-type-in-java-1-5) – Rohit Jain Oct 10 '12 at 09:03
  • See http://stackoverflow.com/questions/11007723/combining-raw-types-and-generic-methods – Zaki Oct 10 '12 at 09:06
  • This kind if implementation is much needed when you integrate your program with applications that uses older Java version or to use older third party APIs. – Satheesh Cheveri Oct 10 '12 at 09:19

2 Answers2

6

Its just for supporting legacy code before generics or java 5.

Generics, introduced in Java SE 5 and Collection has been running since long back. So if you see Collection framework before 1.5 you see ArrayList, there is no generic.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
2

Since using raw types (eg ArrayList without generic parameter) results in warnings if not suppressed, you could also consider to use the "-Werror" flag to "fail on warning":

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javac.html

(though personally, I haven't used this flag yet)

Puce
  • 37,247
  • 13
  • 80
  • 152