确保对象仅在一个列表中

时间:2014-07-01 19:52:34

标签: list reference reference-counting

我遇到了一个非常基本的问题。

我需要确保一个对象只在一个列表中。 例如我有两个列表(伪代码):

Object person = new Object();
List waitingForCoffe = new List();
List waitingForTee = new List();

我如何确保此人在:

  1. 没有清单
  2. 列出waitingForCoffe或
  3. 列出waitingForTee
  4. 但不是同时在展位列表中。 我是否需要确保在我的代码中或已经存在某些东西? 设计模式?

2 个答案:

答案 0 :(得分:0)

您可以使用Set

static HashSet<String> set = new HashSet<String>();
public static void add(ArrayList<String> array, String s)
{
    if(!set.contains(s))
    {
        array.add(s);
    }
}

Set只能有唯一的元素,contains()是O(1),所以你不必担心运行时。如果您想知道如何检查而不是添加,您可以遍历一个数组并将其中的所有元素添加到集合中。然后,您可以循环遍历第二个数组,并查看Set是否包含元素。如果是,意思​​返回true,那么你有一个重复

希望这有帮助!

答案 1 :(得分:0)

你可以让#34; Person&#34;处理列表分配:

public class Person{

    private List currentList = null;

    public void addToList(List newList){

        if (newList == null  || newList == currentList) {
            return;
        }

        if (currentList != null){
            currentList.remove(this);
        }

        currentList = newList;
        newList.add(this);

    }

}