Forum Stats

  • 3,760,221 Users
  • 2,251,664 Discussions
  • 7,871,026 Comments

Discussions

Array of Maps without generic or warnings?

843793
843793 Member Posts: 41,732 Green Ribbon
edited May 22, 2010 6:11PM in Generics
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];

Comments

  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    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
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    Could I see an example? I'm a little lost on doing so.
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    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
This discussion has been closed.