-1

I keep getting java.lang.UnsupportedOperationException when trying to add a new item to the List e.g. Items.add(p); Could you help me in understanding why I am getting this exception?

import java.util.Arrays;
import java.util.List;

public class Item {
    int id; int price;

    public Item(int id, int price) {
        this.id = id;
        this.price = price;
    }

    @Override
    public String toString() {
        return id + ":" + price;
    }

    public static void main(String[] args) {

        List<Item> Items = Arrays.asList(new Item(1, 30), new Item(2, 50), new Item(2, 40)  );

                Item p = Items.stream().reduce(new Item(4,0),(p1, p2) -> {
            p1.price += p2.price;
            return new Item(p1.id, p1.price);
            });

        System.out.println(p);
        Items.add(p);

        Items.stream().parallel().reduce((p1,p2) -> p1.price > p2.price?p1:p2).ifPresent(System.out::println);
    }

}
YCF_L
  • 51,266
  • 13
  • 85
  • 129
J Dev
  • 17
  • 3

1 Answers1

1

Arrays.asList method returns an fixed sized list backed by provided array. You can not add or remove elements from it.

It returns an object of a special class (not ArrayList or LinkedList) which implement List interface. All size changing methods are implemented as to throw java.lang.UnsupportedOperationException.

If you want a List capable of adding further elements create an ArrayList and add your elements to it.

Tanmay Patil
  • 6,802
  • 2
  • 24
  • 45