1

I wanted to test some stuff out about generics in Java so I wrote a method using generics which takes a list and removes every other element. I wrote this method but it gives an UnsupportedOperationException error. What is the problem here?

    Integer[] strArray = new Integer[] {1, 2, 3, 4, 5}; 
    List<Integer> numbers = Arrays.asList(strArray);
    removeOdd(numbers);
    for (Object o : numbers){
         System.out.println( o );
    }
}
        public static <T> void removeOdd ( List<T> list){
            Iterator<T> itr = list.iterator();
            int i = 0;

                while(itr.hasNext())
                {
                    itr.next();
                    i++;
                    if(i % 2 ==1){
                        itr.remove();
                    }
                }   
phcoding
  • 608
  • 4
  • 16

2 Answers2

7

Arrays.asList(T...) creates a fixed sized list. You may replace an element, but not add or remove any.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Ben Schulz
  • 6,101
  • 1
  • 19
  • 15
5

Arrays.asList returns a List whose individual elements may be updated but the addition or removal of elements is not allowed. To create a variable size List, you can use:

List<Integer> numbers = new ArrayList<>(Arrays.asList(strArray));
Reimeus
  • 158,255
  • 15
  • 216
  • 276