我创建了一个名为的自定义类Song
,其中包含 3 个String
变量、一个int
变量和一个ArrayList
项目String
。
现在我对所有变量都有正确的getter和setter等,但是问题是,当我为ArrayList
变量分配一些东西并稍后尝试访问它时,它会抛出一个IndexOutOfBounds
错误,因为它的大小是0。下面是有问题的代码。
是否有可能我没有正确分配变量,或者它的内存位置可能受到清除它的影响?
重要提示:我能够访问和打印其他变量的值,但该ArrayList
变量是唯一失败的变量。
SongClass.java
@Parcel
public class SongClass {
//Other variables defined here
ArrayList <String> verses;
public Song() { /*Required empty bean constructor*/ }
public Song(String var1, String var2, String var3, int var4, ArrayList<String> verses)
{
this.var1= var1;
this.var2= var2;
this.var3= var3;
this.var4= var4;
this.verses = verses;
}
//Getters and Setters below
SongReader.java
//Use to store a collection of Song objects (multiple songs)
private ArrayList<Song> songs = new ArrayList<>(10);
//This array will be assigned to the Song object -> verses
private ArrayList<String> verses = new ArrayList<>(10);
//Other vars to be assigned to song object (String, String, String, int)
...
songs.add(new Song(String var1, String var2, String var3, int var4, verses);
//Important note: I clear the verses `ArrayList` after assigning it to songs. Could this possibly erase it from songs?
verses.clear();
SongDisplay.java
ArrayList<Songs> songs = Parcels.unwrap(intent.getParcelableExtra("Extras"));
...
for (int i = 1; i <= songs.get(0).size(); ++i)
{
TextView textView = new TextView(this);
...
//Error is thrown here
textView.setText(songs.get(0).getVerses().get(i-1);
...
}