This discussion is archived
3 Replies Latest reply: May 22, 2010 3:11 PM by 843793 RSS

Array of Maps without generic or warnings?

843793 Newbie
Currently Being Moderated
How would I create an array of maps without getting an error about a generic type or a warning?

This will give me an error.
HashMap<Integer,Integer> test = new HashMap<Integer,Integer>[5];
This will give me a warning.
HashMap<Integer,Integer> test = new HashMap[5];
  • 1. Re: Array of Maps without generic or warnings?
    843793 Newbie
    Currently Being Moderated
    Dennis_Martinez wrote:
    How would I create an array of maps without getting an error about a generic type or a warning?
    You would not, because it's inherently unsafe; use a list.

    With kind regards
    Ben
  • 2. Re: Array of Maps without generic or warnings?
    843793 Newbie
    Currently Being Moderated
    Could I see an example? I'm a little lost on doing so.
  • 3. Re: Array of Maps without generic or warnings?
    843793 Newbie
    Currently Being Moderated
    Dennis_Martinez wrote:
    Could I see an example? I'm a little lost on doing so.
    I suspect you know how to use lists and ask for an example demonstrating the inherent unsafety. So here it is:
    List<String>[] generic = new List<String>[1]; // assume this works
    List<Integer> ints = new ArrayList<Integer>();
    ints.add(42);
    
    Object[] o = generic;
    o[0] = ints; // this should not work, but it does (erasure)
    
    List<String> strings = generic[0]; // really it's a list of Integers, ohoh
    
    // now you pass that list somewhere completely unrelated and try to get an element:
    String s = strings.get(0); // ClassCastException
    Compare this to:
    String[] strings = new String[1];
    Object[] objects = strings;
    objects[0] = 42; // ArrayStoreException
    With kind regards
    Ben