Question

Here is an example:

public static ArrayList<Integer> position = new ArrayList<Integer>();
public static ArrayList<Integer> new_position = new ArrayList<Integer>();

Collections.copy(new_position, position);
    for (int j = 0; j < position.size(); j++) {

        new_position.get(j) -=4;
    }

I want to copy values and then from my new arraylist subtract 4. How can I make it ? I'm new in java. Also I've got an error such as: The left-hand side of an assignment must be a variable, it refers to nowe_pozycje.get(j) -=4;.

Was it helpful?

Solution

You will have to get() the value, change it, and then set() the new value:

for (int j = 0; j < position.size(); j++) {
    new_position.set(j, new_position.get(j) - 4);
}

An alternative solution could be to skip the whole copying of the list, and instead iterate through the original list, change each value as you go, and add them to the new List:

public static ArrayList<Integer> new_position = new ArrayList<Integer>();
for (Integer i: position) {
    new_position.add(i - 4);
}

OTHER TIPS

If you want to subtract 4 from every element of ArrayList then:

ArrayList<Integer> position = new ArrayList<Integer>();
ArrayList<Integer> new_position = new ArrayList<Integer>();

Collections.copy(new_position, position);
for (int j = 0; j < position.size(); j++) {
    new_position.set(j, (new_position.get(j) - 4)); //remove 4 from element value
}
for (int n : position) new_position.add(n-4);

You don't need to use Collection.copy().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top