我如何实现一个我自己的列表,它不允许重复元素,比如 Set using ArrayList
or LinkedList
?
让我们假设
public class MyList<E> extends AbstractList<E>{
//add
//addAll
//remove
//get
//size
}
我如何实现一个我自己的列表,它不允许重复元素,比如 Set using ArrayList
or LinkedList
?
让我们假设
public class MyList<E> extends AbstractList<E>{
//add
//addAll
//remove
//get
//size
}
@override
public boolean add(..<E>)
{
//implement code to reject duplicates
// returns **false** if object already present in the list
}
Well strictly speaking you can't do that without breaking the List
contract.
Suppose you have:
public class MyList<E> extends AbstractList<E>{
...
}
The fact that you are extending AbstractList
means that you are indirectly implementing List
. And this means that certain operations have to behave in specific ways. For instance List.equals()
is specified as "Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal." But that is totally the wrong semantic for a set, and certainly for a Set
. In a true set, the order of elements is irrelevant to equality.
Now you could ignore this (programs do worse) ... but there is a chance that it could bite you.
Anyway, a more semantically correct implementation of a set using a list would look more like this:
public class MySet<E> implements Set<E> {
private List<E> list = ...
// implement the Set API by delegating to the list object ...
}
Incidentally, the spec of the List.add(E)
operation's return value only a problem if you apply a pedantic and nonsensical reading to the javadocs. The List
javadoc explicitly allows list implementations that refuse to add specific elements. My take is that the phrase "true (as specified by Collection.add(E))" is applies to the case where the add operation actually changes the list. If it doesn't change the list, the Collection.add(E)
method spec actually says that the result should be false
... and so does common sense.
你应该尝试使用LinkedHashSet
而不是MyList