set接口

set

import java.util.*;
public class Test {
	public static void main(String[] args) {
		/*
		Set s = new HashSet();
		s.add("hello");
		s.add("world");
		s.add(new Name("f1","11"));
		s.add(new Integer(100));
		*/
		
		/*
		相同的元素不会被加入
		s.add("hello");
		s.add("hello");
		*/
		//Set 和List容器类都具有Constructor(Collection c)
		//构造方法用以初始化容器
		Set s1 = new HashSet();
		Set s2 = new HashSet();
		s1.add("a");s1.add("b");s1.add("c");
		s2.add("d");s2.add("a");s2.add("b");
		Set sn = new HashSet(s1);
		sn.retainAll(s2);
		Set su = new HashSet(s1);
		su.addAll(s2);
		
		System.out.println(sn);
		
		System.out.println(su);
		
		
		
		
		
		
		
		
		
		/*
		Collection c = new HashSet();
		c.add("hello");
		c.add(new Name("f1","11"));
		c.add(new Name("f2","12"));
		c.add(new Name("f3","13"));
		c.add(new Integer(100));
		c.remove("hello");
		c.remove(new Integer(100));
		
		Iterator i = c.iterator();
		while(i.hasNext()) {
			Name n = (Name)i.next();
			System.out.print(n.getfirstName()+" ");
		}*/
		/*System.out.println(c.remove(new Name("f1","11")));
		System.out.println(c);*/
	}
}
class Name {
	private String firstName,secondName;
	public Name(String firstName,String secondName) {
		this.firstName = firstName;
		this.secondName = secondName;
	}
	public String getfirstName() {return firstName;}
	public String getsecondName() {return secondName;}
	public String toString() {
		return firstName+" "+secondName;
	}
	
	public boolean equals(Object obj) {
		if(obj instanceof Name) {
			Name name = (Name) obj;//强制转换
			return (firstName.equals(name.firstName))&&(secondName.equals(name.secondName));
		}
		return super.equals(obj);
	}
	
	public int hashCode() {
		return firstName.hashCode();
	}
}

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

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

j2sdk api所提供的Set容器类有HashSet,TreeSet等

原文地址:https://www.cnblogs.com/lsswudi/p/11359157.html