创建一个添加方法,如果它重复,则不会添加到列表中?

时间:2014-10-07 05:14:33

标签: java list interface

我正在尝试覆盖将字符串添加到列表的方法。但是如果字符串在列表中是重复的,我希望该方法不添加字符串。如果它不是重复而不是添加,如果不做什么。这是我的代码。我很困惑,为什么它不起作用。

public class Hw6 <T extends Comparable<? super T>> implements     SortedListInterface<T>
{
private ListInterface<T> list;
public Hw6()
{
    list = new LList<T>();
}
@Override
public boolean add(T newEntry) {
    boolean results = false;
    if(!contains(newEntry))
    {
        list.add(newEntry);
        results = true;
    }
    return results;
}
public boolean addPrivate(T newEntry)
{
    int newPosition = Math.abs(getPosition(newEntry));
    return list.add(newPosition, newEntry);
}

@Override
public boolean remove(T anEntry) {
    boolean result = false;
    int position = getPosition(anEntry);
    if (position > 0)
    {
        list.remove(position);
        result = true;
    }
    return result;
}

@Override
public int getPosition(T anEntry) {
    int position = 1;
    int length = list.getLength();

    while((position <= length) && (anEntry.compareTo(list.getEntry(position)) > 0))
    {
        position++;
    }
    if ((position > length) || (anEntry.compareTo(list.getEntry(position)) != 0))
    {
        position = -position;
    }
    return position;
}

@Override
public T getEntry(int givenPosition) {
    return list.getEntry(givenPosition);
}

@Override
public boolean contains(T anEntry) {
    boolean found = false;
    for (int index = 0; !found && (index < getLength()); index++)
    {
        if (anEntry.equals(list.getEntry(index)))
            found = true;
    }
    return found;
}

@Override
public int getLength() {
    // TODO Auto-generated method stub
    return list.getLength();
}

@Override
public boolean isEmpty() {
    if(getLength() == 0)
        return true;
    else
        return false;
}

@Override
public boolean isFull() {
    return false;
}

public static void main(String args[])
{
    LList<String> list = new LList<String>();
    list.add("brad");
    list.add("nick");
    list.add("brad");
    for(int i = 1; i <= list.getLength(); i++)
    {
        System.out.println(list.getEntry(i));
    }
}

}

这是我的输出。我不希望它添加brad因为它是重复的

布拉德 缺口 布拉德

1 个答案:

答案 0 :(得分:1)

这是因为在您的测试中您正在创建一个List对象,但您应该创建一个Hw6对象。