Devrath
Devrath

Reputation: 42824

Manipulating contents of array

I have a piece of code where I am trying to manipulate the contents of an array

loopArrayValuesToRemove(mVal.getValues());

Here I am trying to remove the contents of the array of values

private Values[] loopArrayValuesToRemove(Values[] values) {

    List<Values> files = new ArrayList<>(Arrays.asList(values.clone()));
    Iterator<Values> iterator = files.iterator();
    while(iterator.hasNext()) {
        Values mVal = iterator.next();
        if(!mVal.isCheckedLocally()){
            iterator.remove();
        }
        // other operations
    }
    Values[] mvals = files.toArray(new Values[files.size()]);

    return mvals;
}
  1. Since I am creating the new object even if I manipulate Values[], mVal.getValues() contents are not modified.
  2. It's a Silly question, but I am stuck at this. as I cannot change the response to arrayList in server at (mVal.getValues())

Upvotes: 2

Views: 114

Answers (2)

Nikolas
Nikolas

Reputation: 44408

As I understand your question, your goal is to remove instances from the List which isCheckedLocally() returns true,

You can use the Stream API since Java 8.

mVal = mVal.stream()
    .filter(i -> i.isCheckedLocally())
    .collect(Collectors.toList());

Upvotes: 1

Kayaman
Kayaman

Reputation: 73558

You're going to have to write it as

mVal.setValues(loopArrayValuesToRemove(mVal.getValues()));

Due to Java passing references by value, you can't change the array itself inside the method. Contents can be changed, but if the size changes it can't be done.

Upvotes: 2

Related Questions