-4

My function is update the ArrayList, but doesn't update the boolean, it's very weird!

I just not understand, or them both updates, or them both not.

private ArrayList<String> arrayList = new ArrayList<>();
private boolean isEmpty = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNames(arrayList, isEmpty);
    Log.d("status", arrayList.size() + " " + isEmpty);

}

private void addNames(ArrayList<String> names, boolean empty) {
    names.add("Moshe");
    names.add("Noa");
    names.add("Haim");
    empty = false;
}

How can i update the isEmpty variable? (this.isEmpty = false; is not good for me, i need another way)

3 Answers3

1

You want to set the field to the arg, so empty=false should instead be

this.isEmpty = empty

As just setting empty = false sets the passed in argument 'empty' to false rather than the field

AleksW
  • 703
  • 3
  • 12
0

You are using the wrong variable. empty is the method parameter which has method scope only. The class scope variable is isEmpty. You don't need to use this in this case.

use isEmpty = true;

In your scenario, you don't even need to pass the arguments in that method. Those variables are global and can be accessed without passing them as an argument. Also isEmpty is unnecessary when you could use arrayList.isEmpty()

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
0

You don't need to any isEmpty field, you can check on the fly by calling arrayList.isEmpty().

private List<String> arrayList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNames(arrayList);
    Log.d("status", arrayList.size() + " " + arrayList.isEmpty());

}

private void addNames(List<String> names) {
    names.add("Moshe");
    names.add("Noa");
    names.add("Haim");
}

Look here for further information

Andreas
  • 430
  • 5
  • 21