我正在尝试覆盖将字符串添加到列表的方法。但是我想如果字符串是列表中的重复项,则不添加字符串的方法。如果不是重复项,那么如果没有则不添加。这是我的代码。我只是感到困惑,为什么它不起作用。
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));
}
}
}
这是我的输出。我不希望它添加曲头钉,因为它是重复的
布拉德·尼克·布拉德
这是因为在测试中您正在创建一个LList对象,但是您应该在创建一个Hw6对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句