【发布时间】:2013-05-03 17:54:51
【问题描述】:
我有一个带有存储国家/地区的数组列表的国家/地区。我创建了一个 get 和 set 来从数组列表中的指定索引添加和获取项目,但我不会工作。每当我从 arraylist 调用索引时,我都会得到一个超出范围的异常,因为数组是空的或者至少看起来是空的。
public class country extends Application {
public ArrayList<country> countryList = new ArrayList<country>();
public String Name;
public String Code;
public String ID;
public country()
{
}
public country(String name, String id, String code)
{
this.Name = name;
this.ID = id;
this.Code = code;
}
public void setCountry(country c)
{
countryList.add(c);
}
public country getCountry(int index)
{
country aCountry = countryList.get(index);
return aCountry;
}
调用我使用的设置器。我在 for 循环中执行此操作,因此它添加了 200 多个元素
country ref = new country();
ref.setCountry(new country (sName, ID, Code));
那么当我想得到一个索引时
String name = ref.countryList.get(2).Name;
我做了同样的事情,但使用了本地数组列表,它填充得很好,我能够显示名称,所以数据源不是问题,无论我做错了设置并在国家类的数组列表中获取数据
【问题讨论】:
-
与国家/地区数组列表一起创建的本地数组列表包含 200 多个对象,所以这不是问题。 resultbox.setText(countryNames.get(2).Name); // 打印一个名字 resultbox.setText(ref.getCountry(2).Name); //返回错误
-
执行 ref.countryList.get(0).Name 因为您只在列表中添加了一项;
-
向我们展示添加 200 多个对象的代码。您很可能会将其添加到不同的列表中。
标签: java android arraylist getter-setter indexoutofboundsexception