从ArrayList添加/删除值以获取唯一值

时间:2015-03-10 21:16:15

标签: java android arraylist

我正在开发一个使用ArrayList来填充ListView的应用。我为ListView使用自定义类。我想为ArrayList添加/删除Listview。我对此应用的目标是控制列表项元素,如果它存在于ArrayList中,或者它在ArrayList中不存在{1}}添加列表项。

为了解释我的情况,我在下面粘贴了我的代码;

这是我的自定义类;

public class NDListItem {
    String textdata;
    public NDListItem(String textdata) {
        this.textdata = textdata;
    }
}

这是我使用班级的方法。名称参数来自另一个活动。它来得当。我使用for循环来解决这个问题并且无法得到我想做的事情。我阅读了一些文档并找到了另一种解决方对我的班级使用equals和hash-code方法可能会完成我的工作,但我不知道如何使用它。

编辑:在第二个代码块中添加一些解释和myItems说明。

public void addLayersection(String name) {

//MyList already defined on the scope..
//MyList looks like this
// ArrayList<NDListItem> myItems = new ArrayList<>();

    NDListItem listItem = new NDListItem(name);
  if (myItems.size() == 0) {
        myItems.add(listItem);
    } else {
    if(myItems.contains(listItem))
        {
            myItems.add(listItem);
        }
        else
        {
            myItems.remove(listItem);

        }

    }

    myAdapter.notifyDataSetChanged();
}

EDIT2

我更新了我的Class for equals方法。它工作得非常好,但只是我添加到ArrayList的第一项工作。我想为每件物品做这项工作

public class NDListItem {
    String textdata;

    public NDListItem(String textdata) {
        this.textdata = textdata;
    }

    public boolean equals(Object o) {
        if (o == null) return false;
        //if(!(o instanceof) NDListItem) return false;
        if (!(o instanceof NDListItem)) return false;

        NDListItem other = (NDListItem) o;
        if (!this.textdata.equals(other.textdata))

            return false;
        else


        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

好的,根据您提供的详细信息,

由于自定义类.equals()中没有NDListItem覆盖方法

您的列表将根据引用比较对象,因此只需覆盖自定义.equals()类中的NDListItem方法

喜欢,(仅用于理解的伪代码)

@Override
public boolean equals(Object obj) {     
   NDListItem ndListItemObject = (NDListItem) obj;          
   return this.textdata.equalIgnoreCase(ndListItemObject.textdata);
}

现在,.contains()方法可以根据需要在自定义对象列表上使用。

因为,您在textdata属性上进行了对象比较。