How to add an integer element to ArrayList of wildcards in Generics?

后端 未结 5 482
忘了有多久
忘了有多久 2021-01-17 00:44

I have a ArrayList generic wildcards type, which is taking Number as extends. I am trying to add the integer values to the ArrayList.

Buts it\'s giving me an error

5条回答
  •  耶瑟儿~
    2021-01-17 01:30

    You Should do something like this

    ArrayList numberList = new ArrayList();
    numberList.add(100);
    

    for java 8, you can use stream(),

    // to resolve your read problem cause by  
    
    ArrayList arrayList = new ArrayList();
    arrayList.add(100);
    List list = arrayList.stream().map(e->(Integer) e).collect(Collectors.toList());
    System.out.println(list);
    

提交回复
热议问题