javaarraylistremoveall

can't use method removeAll in Java list


I have a list of integers 1,2,3,4 in one list, called a1temp and want to use the items in GA to delete the same items in a1temp, using a1temp.removeAll(GA);

Basically, Got a list of items in list A want to remove same items in list B

So I've got my code

I'd appreciate any help possible. thanks in advance

Obviously, importing couple of things, import java.util.ArrayList; import java.util.List;

class R{

List<Integer> GA = new ArrayList<Integer>();
List<Integer> a1temp = List.of(1, 2, 3, 4);
int a1 = 0;
int a2 = 0;
int a3 = 0;
int a4 = 0;

// if a1 is not 0 (has another value) & it's not already in GA will check it's value and add it to GA.

public void checkGA() {
     if (a1 != 0) {
           if (!GA.contains(a1)) {
               GA.add(a1);
               }}}

// remove items from listA with items from listB.

public void placeGA() {

        // Check if GA has some value.
        if (GA.size() > 0) {
            try {
               //Here is where the problem appears.
               // "a1temp list" should be getting the items removed  
               // when "a1temp" has same items as "GA list"
                a1temp.removeAll(GA);
            }catch (Exception e){
                System.out.println("Can't delete");
}}}
public class Main {
    public static void main(String[] args) {
        R r1 = new R();
        r1.a1 = 4;
        r1.a2 = 3;
        r1.a3 = 2;

        // We add items from a1, a2 & a3 to GA list
        r1.checkGA();
        System.out.println("Show GA");
        // Shows current items in GA list
        System.out.println(r1.GA);

console:

Show GA

[4, 3, 2]

System.out.println("show a1temp);
// defined before a1temp = List.of(1, 2, 3, 4);
System.out.println(r1.a1temp);

console:

Show a1temp

[1, 2, 3, 4]

// try to delete items 2, 3, 4.
r1.placeGA();
}

console Can't delete.


error showed: Error:

Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.removeAll(ImmutableCollections.java:151) at R.placeGA(Main.java:124) at Main.main(Main.java:255)

So I've tried deleting the items 2, 3, 4 from a1temp, so it would show only the item 1 on the list.

Can anyone tell my why is not working?

Thanks in advance. Its my first post.

Tried to remove items 2, 3, 4 from one list, but getting an error.


Solution

  • From the JavaDoc for List

    Unmodifiable Lists

    The List.of and List.copyOf static factory methods provide a convenient way to create unmodifiable lists. The List instances created by these methods have the following characteristics:

    So you need to change it as follows:

    List<Integer> a1temp = new ArrayList<>(List.of(1, 2, 3, 4));