[java] Array of ArrayListMyClass creation :S

Recommended Posts

tufflax    504
Hey! I'm trying to create an array of ArrayLists. But I'm doing something wrong because I can't do it without getting warnings. ArrayList<MyClass>[] list; list = new ArrayList<MyClass>[100]; <- error: generic array creation list = new ArrayList[100]; <- warning: unchecked conversion for (...) list[i] = new ArrayList<MyClass>; What am I doing wrong?

Share on other sites
Guest Anonymous Poster
I'm still using 1.4 here so I can't check this out but my gut feeling is that you probably can't do this, purely from the compilers point of view. It probably barfs on the combination. I'd happily be proven wrong though. Just live with the warnings and do it without the generics ...

D.

Share on other sites
Guest Anonymous Poster
I'm still using 1.4 here so I can't check this out but my gut feeling is that you probably can't do this, purely from the compilers point of view. It probably barfs on the combination. I'd happily be proven wrong though. Just live with the warnings and do it without the generics ...

D.

Share on other sites
Fred304    382
Simply use an ArrayList of generic ArrayLists, that should work.

Share on other sites
Guest Anonymous Poster
Quote:
 Original post by RayNbowSomething I found about array generics:Java Technology Forums - Clarification for Array Types and generics

well there you go. Generics were always a bit of a hack anyway. I was under the impression when I first started using them (exclusively 1.5 in work) that the RE actually 'knew' about them but its actually quite possible I discovered to compile 1.5 source containing generics to conform to 1.4 bytecode, so its literally just a compile time thing. They're useful for sanity checking while coding, and not having to write out all those casts, little else.

D.

Share on other sites
capn_midnight    1707
yeah, this is some funness right here:
ArrayList<String> arrStr = new ArrayList<String>();ArrayList<Integer> arrInt = new ArrayList<Integer();arrStr.add("Wot wot?!?");arrInt.add(new Integer(13));ArrayList arrObj = arrInt; //this is fine, no problem herearrStr = (ArrayList<String>)arrObj; //so far, no complaints from compiler or runtime.System.out.println(arrStr.get(1)); //RUNTIME KABOOM!!!

To me, a proper generics system should definitely not allow the 6th line, and probably shouldn't allow the 5th line, with all of this checking at COMPILE time, not runtime.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account