The Set Interface
A Set
is a Collection
that cannot contain duplicate elements. It models the mathematical set abstraction. The Set
interface containsonly methods inherited from Collection
and adds the restriction that duplicate elements are prohibited. Set
also adds a stronger contract on the behavior of the equals
and hashCode
operations, allowing Set
instances to be compared meaningfully even if their implementation types differ. Two Set
instances are equal if they contain the same elements.
---set 接口不可以保存重复值。如果两个对象equals则为相等。
The List Interface
A List
is an ordered Collection
(sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection
, the List
interface includes operations for the following:
---List 集合里的元素是有序的。并且可以包含相同值。
我们用以下的例子来说明:
package com.wsx;
import java.util.*;
public class Test {
public static void main(String[] a){
Collection c=new ArrayList();
// Collection c=new HashSet();
c.add("Hello");
c.add(new Name("f1", "l1"));
c.add(new Integer(100));
c.add("Hello");
c.add(new Integer(101));
System.out.println(c.size());
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;
}
}
输出结果为:
5
[Hello, f1 l1, 100, Hello, 101]
package com.wsx;
import java.util.*;
public class Test {
public static void main(String[] a){
//Collection c=new ArrayList();
Collection c=new HashSet();
c.add("Hello");
c.add(new Name("f1", "l1"));
c.add(new Integer(100));
c.add("Hello");
c.add(new Integer(100));
System.out.println(c.size());
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;
}
}
输出结果为:
3
[100, f1 l1, Hello]