set 检索效率低,插入和删除元素效率高。
list 检索效率高,插入和删除元素效率低。
list调用contains方法时 ,会遍历所有元素,并调用equals()方法,equals()方法返回true, 则contains 返回ture ,时间复杂度为O(n)
set调用contains方法时,会比较所有元素的hashcode方法,当hashcode方法返回true时再比较equals ,也返回true时,contains返回true,。时间复杂度为O(1) 。
public class Dog {
private String id;
private String name;
public Dog(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
Dog dog = (Dog) obj;
if(id.equals(dog.getId())&&
name.equals(dog.getName())){
return true;
}else{
return false;
}
}
@Override
public int hashCode() {
return (id+"_"+name).hashCode();
}
}
@Test
public void listContains(){
List<Dog> list = new ArrayList<>();
list.add(new Dog("1","we"));
list.add(new Dog("2","erer"));
System.out.println(list.contains(new Dog("1","we")));
}
@Test
public void setContains(){
Set<Dog> set = new HashSet<>();
set.add(new Dog("1","we"));
set.add(new Dog("2","erer"));
System.out.println(set.contains(new Dog("1","we")));
}
源码
list
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
set
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
网友评论