How can I add to List<? extends Number> data structures?

前端 未结 6 964
暗喜
暗喜 2020-11-22 02:19

I have a List which is declared like this :

 List foo3 = new ArrayList();

I tried to add 3 to foo3.

6条回答
  •  醉话见心
    2020-11-22 02:56

    You can fudge it by creating a reference to the List with a different type.

    (These are the "unsafe casts" mentioned by sepp2k.)

    List list = new ArrayList();
    
    // This will not compile
    //list.add(100);
    
    // WORKS, BUT NOT IDEAL
    List untypedList = (List)list;
    // It will let you add a number
    untypedList.add(200);
    // But it will also let you add a String!  BAD!
    untypedList.add("foo");
    
    // YOU PROBABLY WANT THIS
    // This is safer, because it will (partially) check the type of anything you add
    List superclassedList = (List)(List)list;
    // It will let you add an integer
    superclassedList.add(200);
    // It won't let you add a String
    //superclassedList.add("foo");
    // But it will let you add a Float, which isn't really correct
    superclassedList.add(3.141);
    // ********************
    // So you are responsible for ensuring you only add/set Integers when you have
    // been given an ArrayList
    // ********************
    
    // EVEN BETTER
    // If you can, if you know the type, then use List instead of List
    List trulyclassedList = (List)(List)list;
    // That will prevent you from adding a Float
    //trulyclassedList.add(3.141);
    
    System.out.println("list: " + list);
    

    Because untypedList, superclassedList and trulyclassedList are just references to list, you will still be adding elements to the original ArrayList.

    You don't actually need to use (List) in the example above, but you might need it in your code, depending on the type of list you were given.

    Note that using ? will give you compiler warnings, until you put this above your function:

    @SuppressWarnings("unchecked")
    

提交回复
热议问题