I'm facing such a bizarre behavior in Java(Android Studio). What I've been doing is populating an ArrayList of Strings with some data. Then instantiate an object using that ArrayList, the new object is then added to another ArrayList of the object type.
Here is the constructor of the class:
protected ArrayList<String> languages;
public Person(ArrayList<String> languages)
{
this.languages=languages;
}
Then in the Activity, I use two ArrayLists, one called languages and one called Persons. The languages ArrayList is passed to a new object added in Persons.
ArrayList<String> languages=new ArrayList<String>();
ArrayList<Person> Persons=new ArrayList<Person>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
.
.
.
.
.
.
english=(CheckBox)findViewById(R.id.english);
if(anglais.isChecked())
languages.add(english.getText().toString());
Persons.add(new Person(languages));
Log.i("test: ",Persons.get(0).getLangues().get(0)); // Will show English
languages.clear(); // Here I clear the languages ArrayList so I can add new languages for another person
Log.i("test: ",Persons.get(0).getLangues().get(0)); // Produces an exception.
}
});
}
As you can see, I populate languages first, then populate Persons with a new object using languages. In order to add another person with different languages(for example) I must clear the languages ArrayList so I can re-use it.
To test what actually happens, I found out that the first Log will show the added langauge(notice that I am getting the language from Persons, and not languages). However, the second Log will produce an exception stating that the langauges array IN Person class is empty(cleared). What could be causing the clear function not to just clear the languages array, but also the languages array in Person class?