• 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]
    	}
    }
    
  • 相关阅读:
    MySQL中的InnoDB中产生的死锁深究
    MySQL中的触发器应用
    你除了在客户端上会使用Cookie,还能使用哪些可以作为数据缓存呢?
    js中实现输入框类似百度搜索的智能提示效果
    linux系统中启动mysql方式已经客户端如和连接mysql服务器
    linux系统安装mysql数据库
    Linux中实用的命令
    Linux下安装jdk中遇到的坑
    Git初始化配置以及配置github
    springboot中配置文件使用2
  • 原文地址:https://www.cnblogs.com/bosongokay/p/6770243.html
Copyright © 2020-2023  润新知