2

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;.

2
  • Get the value, subtract from it, and put it back. An ArrayList is not an array. Commented Apr 6, 2014 at 15:26
  • subtract 4 means? what exactly you want to do? do you want to remove 4 elements? Commented Apr 6, 2014 at 15:29

3 Answers 3

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

1
for (int n : position) new_position.add(n-4);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.