import java.util.*;public class BasicContainer {
public static void main(String[] args) {
Collection c = new HashSet();
c.add("hello");
c.add(new Name("f1","l1"));
c.add(new Integer(100));
c.remove("hello");
c.remove(new Integer(100));
System.out.println
(c.remove(new Name("f1","l1")));
System.out.println(c);
}
}class Name {
private String firstName,lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName; this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String toString() { return firstName + " " + lastName; }
public boolean equals(Object obj) {
if (obj instanceof Name) {
Name name = (Name) obj;
return (firstName.equals(name.firstName))
&& (lastName.equals(name.lastName));
}
return super.equals(obj);
}
public int hashCode() {
return firstName.hashCode();
}
}
一个很简单的集合小程序 使用HashSet() remove 一个集合里的元素Name("f1","l1") 需要重写equals() 和hashCode()两个method 但是在使用ArrayList() 或者 LinkedList()时 仅仅重写equals()方法就可以remove Name("f1","l1") 这是问什么呢? HashSet(), ArrayList(), LinkedList()不是都继承自Collection 接口么?
public static void main(String[] args) {
Collection c = new HashSet();
c.add("hello");
c.add(new Name("f1","l1"));
c.add(new Integer(100));
c.remove("hello");
c.remove(new Integer(100));
System.out.println
(c.remove(new Name("f1","l1")));
System.out.println(c);
}
}class Name {
private String firstName,lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName; this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String toString() { return firstName + " " + lastName; }
public boolean equals(Object obj) {
if (obj instanceof Name) {
Name name = (Name) obj;
return (firstName.equals(name.firstName))
&& (lastName.equals(name.lastName));
}
return super.equals(obj);
}
public int hashCode() {
return firstName.hashCode();
}
}
一个很简单的集合小程序 使用HashSet() remove 一个集合里的元素Name("f1","l1") 需要重写equals() 和hashCode()两个method 但是在使用ArrayList() 或者 LinkedList()时 仅仅重写equals()方法就可以remove Name("f1","l1") 这是问什么呢? HashSet(), ArrayList(), LinkedList()不是都继承自Collection 接口么?
你找下这两种数据结构的源代码看一下就知道为什么了。
remove的第一步是要在container里面找是否有这个目标对象啊 寻找的过程就是遍历container里面的元素并且调用equals来判断对象是否相等
所以如果经常添加或者删除用linkedList比ArrayList效率高。
如果是按索引查询,用ArrayList比linkedList效率高。
所以根据需求用不同的集合。