Java容器之Set接口

Set 接口:

  1. Set 接口是 Collection 的子接口,Set 接口没有提供额外的方法,但实现 Set 接口的容器类中的元素是没有顺序的,且不可以重复;

  2. Set 容器可以与数学中的“集合” 的概念相对应;

  3. J2SDK API 中所提供的 Set 容器类有 HashSet、TreeSet等;

举例分析,如:

Demo_1:

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;
	}
	@Override
	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);
	}
	@Override
	public int hashCode() {
		return firstName.hashCode();
	}
}
public class Test {
	public static void main(String[] args) {
		HashSet ss = new HashSet();
		ss.add("Hello");
		ss.add("World");
		ss.add(new Integer(100));
		ss.add(new Name("f1", "l1"));
		ss.add("Hello");
		ss.add(new Name("f1", "l1"));
		System.out.println(ss); // 输出:[Hello, 100, f1  l1, World]
	}
}

 Demo_2:

public class Test {
	public static void main(String[] args) {
		HashSet<String> s1 = new HashSet<String>();
		HashSet<String> s2 = new HashSet<String>();
		s1.add("a");s1.add("b");s1.add("c");
		System.out.println(s1); // 输出:[a, b, c]
		s2.add("d");s2.add("a");s2.add("b");
		System.out.println(s2); // 输出:[a, b, d]
		HashSet<String> sn = new HashSet<String>(s1);
		System.out.println(sn); // 输出:[a, b, c]
		sn.retainAll(s2); // 求集合交集
		System.out.println(sn); // 输出:[a, b]
		HashSet<String> su = new HashSet<String>(s1); // Set 和 List 容器类都具有 Collstructor(Collection c)
		System.out.println(su); // 输出:[a, b, c]
		su.addAll(s2);
		System.out.println(su); // 输出:[a, b, c, d]
	}
}
原文地址:https://www.cnblogs.com/bosongokay/p/6770243.html