[java] Array of ArrayListMyClass creation :S

Started by
5 comments, last by capn_midnight 17 years, 11 months ago
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 = new ArrayList<MyClass>; What am I doing wrong?
Advertisement
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.
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.
Simply use an ArrayList of generic ArrayLists, that should work.
Something I found about array generics:
Java Technology Forums - Clarification for Array Types and generics
Quote:Original post by RayNbow
Something 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.
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.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

This topic is closed to new replies.

Advertisement