如何在android中使用简单的getter和setter

问题描述 投票:0回答:3

我有一个国家类,它有一个存储国家/地区的数组列表。我已经创建了一个 get 和 set 来添加和获取数组列表中指定索引的项目,但我不会工作。每当我从数组列表中调用索引时,我都会收到越界异常,因为数组为空或至少看起来是空的。

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;

我做了同样的事情,但使用了本地数组列表,它填充得很好,我能够显示名称,所以数据源不是问题,无论我做了错误的设置并在国家类的数组列表中获取数据

java android arraylist getter-setter indexoutofboundsexception
3个回答
0
投票

您访问了一个不存在的索引。您只添加一个国家,因此您只能访问:

String name = ref.countryList.get(0).Name;

你真的应该重新考虑你的设计。

public
属性并不是最佳实践方式。这就是为什么你应该首先编写 getter 和 setter 方法的原因。

你应该这样做:

public Country getCountry(int index)
{
    if(index < countryList.size())
    {
        return countryList.get(index);
    }
    return null;
}

0
投票

String name = ref.countryList.get(2).Name;
中,您试图获取列表中的 third 元素,而您只添加了 one...
应该是
String name = ref.countryList.get(0).Name;
,之前需要检查是否没有收到空指针异常


-1
投票

执行

ref.countryList.get(0).Name
,因为您只在列表中添加了 1 项。

我会建议更多类似的

 ref.countryList.get(0).getName()
© www.soinside.com 2019 - 2024. All rights reserved.