Set接口与实现类

Set子接口

  • 特点:无序、无下标、元素不可重复。
  • 方法:全部继承自Collection中的方法。

Set实现类

  • HashSet【重点】:

    • 基于HashCode实现元素不重复。
    • 当存入元素的哈希吗相同时,会调用equals进行确认,如结果为true,则拒绝后者存入。
    • 基于HashCode计算元素存放位置。
  • TreeSet:

    • 基于排列顺序实现元素不重复。
    • 实现类SortedSet接口,对集合元素自动排序。
    • 元素对象的类型必须实现Comparable接口,指定排序规则。
    • 通过CompareTo方法确定是否为重复元素。
  • Set接口使用:

    public class SetTest {public static void main(String[] args) {Set<String> set = new HashSet<>();//添加数据System.out.println("-----添加数据-----");set.add("小米");set.add("苹果");set.add("华为");System.out.println("数据个数:"+set.size());System.out.println(set.toString());// 删除数据System.out.println("-----删除数据-----");set.remove("小米");System.out.println(set.toString());// 遍历// 使用增强forSystem.out.println("-----增强for-----");for(String string : set){System.out.println(string);}// 使用迭代器System.out.println("-----使用迭代器-----");Iterator<String> it = set.iterator();while (it.hasNext()){System.out.println(it.next());}// 判断System.out.println("-----判断-----");System.out.println(set.contains("华为"));System.out.println(set.isEmpty());}
    }
    

    • HashSet接口的实现:
    // HashSet集合的使用
    // 储存结构:哈希表(数组+链表+红黑树)
    public class HashSettest {public static void main(String[] args) {// 新建集合               这里的尖括号在JDK1.8之后可以不用写HashSet<String> hashSet = new HashSet<>();// 添加元素System.out.println("-------添加元素-------");hashSet.add("刘德华");hashSet.add("梁朝伟");hashSet.add("林志颖");hashSet.add("周润发");hashSet.add("刘华强");hashSet.add("刘德华"); // 这时的"刘德华"是添加不进去的,因为HashSet不允许有重复System.out.println("元素个数:"+hashSet.size());// 这里的元素个数是“5”System.out.println(hashSet.toString());// 输出“[梁朝伟, 林志颖, 周润发, 刘华强, 刘德华]”// 删除数据System.out.println("-------删除数据-------");hashSet.remove("刘德华");System.out.println("删除之后:"+hashSet.toString());// 遍历操作System.out.println("=============遍历操作=============");// 增强forSystem.out.println("-------增强for-------");for (String string:hashSet) {System.out.println(string);}// 使用迭代器System.out.println("-------迭代器-------");Iterator<String> it = hashSet.iterator();while(it.hasNext()){System.out.println(it.next());}// 判断System.out.println("-------判断-------");/** contains()判断集合里有没有某个元素 返回 true 或 false* isEmpty()判断此集合是否为空 返回 true 或 false* */System.out.println(hashSet.contains("刘华强"));System.out.println(hashSet.isEmpty());}
    }

    • HashSet存储(add)
    public class Demo3{public static void main(String[] args){// 创建集合HashSet<Person> person = new HashSet<>();// 添加集合Person p1 = new Person("刘德华",20);Person p2 = new Person("林志玲",22);Person p3 = new Person("梁朝伟",25);person.add(p1);person.add(p2);person.add(p3);// person.add(p2); 不可以添加进去person.add(new Person("梁朝伟",25));// 可以添加进去System.out.println("元素个数:"+person.size());System.out.println(person.toString());/*存储过程(重复的依据)(1)根据Hashcode,计算保存的位置,如果此位置为空,则直接保存,如果不为空执行第二步(2)在执行equals方法,如果equals方法为true,则认为是重复,否则,形成链表@Overridepublic int hashCode(){int n1 = this.name.hashCode();int n2 = this.age;return n1+n2;}@Overridepublic boolean equals(Object obj){if(this==obj){return true;}if(obj==null){return flase;}if(obj instanceof Person){Person p = (Person)obj;if(this.name.equals(p.getName())&&this.age==p.getAge())                  {return true;}}return super.equals(obj);}@Overridepublic int hashCode(){(1)31是一个质数,减少散列冲突(2)31提高执行效率 31*i(i<<5)-i}*/// 删除操作person.remove(p1);person.remove(ew Person("刘德华",20));System.out.println("删除之后:"+persons.size());// 遍历// 使用增强forfor(Person per : person){System.out.println(per.toString());}// 迭代器Iterator<POerson> it = person.iterator();while(it.hasNext()){System.out.println(it.next());}// 判断System.out.println(person.contains(p1));System.out.println(person.isEmpty());}
    }
    

    TreeSet的使用

    public class Demo4{public static void main(String[] args){// 创建集合TreeSet<String> treeSet = new TreeSet<>();// 添加集合treeSet.add("xyz");treeSet.add("abc");treeSet.add("hello");treeSet.add("xyz");System.out.println("元素个数:"+treeSet.size());System.out.println(treeSet.toString());// 删除treeSet.remove("xyz");System.out.println("删除之后:"+treeSet.size());// 遍历// 使用增强forfor (String string : treeSet){System.out.println(string);}System.out.println("-----------------------");// 使用迭代器Iterator<String> it = treeSet.iterator();while(it.hasNext()){System.out.println(it.next());}// 判断System.out.println(treeSet.contains("abc"));}
    }
    
    • 实例集合
    public class Person implements Comparable<Person>
    {String name;int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Person(String name, int age) {this.name = name;this.age = age;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (!(o instanceof Person)) return false;Person person = (Person) o;return age == person.age &&Objects.equals(name, person.name);}@Overridepublic int hashCode() {return Objects.hash(name, age);}/*** Compares this object with the specified object for order.  Returns a* negative integer, zero, or a positive integer as this object is less* than, equal to, or greater than the specified object.** <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==* -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>.  (This* implies that <tt>x.compareTo(y)</tt> must throw an exception iff* <tt>y.compareTo(x)</tt> throws an exception.)** <p>The implementor must also ensure that the relation is transitive:* <tt>(x.compareTo(y)&gt;0 &amp;&amp; y.compareTo(z)&gt;0)</tt> implies* <tt>x.compareTo(z)&gt;0</tt>.** <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt>* implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for* all <tt>z</tt>.** <p>It is strongly recommended, but <i>not</i> strictly required that* <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>.  Generally speaking, any* class that implements the <tt>Comparable</tt> interface and violates* this condition should clearly indicate this fact.  The recommended* language is "Note: this class has a natural ordering that is* inconsistent with equals."** <p>In the foregoing description, the notation* <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical* <i>signum</i> function, which is defined to return one of <tt>-1</tt>,* <tt>0</tt>, or <tt>1</tt> according to whether the value of* <i>expression</i> is negative, zero or positive.** @param o the object to be compared.* @return a negative integer, zero, or a positive integer as this object* is less than, equal to, or greater than the specified object.* @throws NullPointerException if the specified object is null* @throws ClassCastException   if the specified object's type prevents it*                              from being compared to this object.*/@Overridepublic int compareTo(Person o) {int n1 = this.getName().compareTo(o.getName());int n2 = this.age-o.getAge();return n1==0 ? n2:n1;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
    }public static void main(String[] args) {// 因为TreeSet是一种红黑树的存储结构,一次性有两个数据传进去,equals比较不了p1与p2,所以添加会报错。这里我们会重写compareTo方法用三目运算符来判断返回。TreeSet<Person> t = new TreeSet<>();Person p1 = new Person("哈哈",20);Person p2 = new Person("hh",18);Person p3 = new Person("zz",90);Person p4 = new Person("hh",20);t.add(p1);t.add(p2);t.add(p3);t.add(p4);System.out.println(t.toString());
    }
    

Comparator接口

  • 还是TreeSet集合的使用

  • Comparator实现定制比较(比较器)

  • Comparable 可比较的

  • 实例1:

    public static void main(String[] args){// 创建集合,并指定比较规则// 使用一个匿名内部类TreeSet<Person> Persons = new TreeSet<>(new Comparator<Person>(){@Overridepublic int compare(Person o1,Persono2){int n1 = o1.getAge()-o2.getAge();int n2 = o1.getName().compareTo(o2.getName());return n1==0?n2:n1;}});Person p1 = new Person("哈哈",20);Person p2 = new Person("hh",18);Person p3 = new Person("zz",90);Person p4 = new Person("hh",20);persons.add(p1);persons.add(p2);persons.add(p3);persons.add(p4);System.out.println(persons.toString());
    }
    

使用TreeSet集合实现字符串按照长度进行排序

TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>(){@Overridepublic int compare(String o1,String o2){int n1 = o1.length()-o2.length();int n2 = o1.compareTo(o2);return n1==0?n2:n1;}
});
// 添加数据
treeSet.add("helloworld");
treeSet.add("pingguo");
treeSet.add("lisi");
treeSet.add("zhangsan");
treeSet.add("beijing");
treeSet.add("cat");
treeSet.add("nanjing");
treeSet.add("xian");System.out.println(treeSet.toString());

Java-----Set接口与实现类相关推荐

  1. Java容器接口及其实现类(JCF)

    参考文章,官方文档 Java容器接口分为两个部分,一个是最基础的接口 java.util.Collection,另一部分接口是基于java.util.Map 继承Collection的接口 java. ...

  2. java面向对象 接口和实现类_类实现java面向对象上:接口

    最近应用开发的过程中出现了一个小问题,顺便记录一下原因和方法--类实现 10.接口: 接口的设计:        1.应用接口处理多继承:        2.应用接口为外部类添加功能:        ...

  3. Java获取接口所有实现类的方式

    有时候,根据业务逻辑的需求,我们想要获取到某个接口的所有实现类.在这里大致介绍两种方式: 1.借助Spring容器实现 Spring作为一个容器,管理着一个项目中所有经过配置的Java类(xml配置文 ...

  4. 【Email】Java发送邮件接口与配置类

    说明 这文章17年的,不知道为啥,被放到草稿箱了.现在发表下. 转载请注明出处:http://blog.csdn.net/qq_26525215 本文源自[大学之旅_谙忆的博客] 可能最近写博客时间不 ...

  5. java sortedmap_SortedMap接口的实现类TreeMap介绍和实现Comparator自定义比较器

    与SortedSet接口类似,SortedMap也是一个结构,待排序的Map,其一个比较常用的实现类是TreeMap. TreeMap的put(K key, V value)方法在每添加一个元素时,都 ...

  6. java接口与类相同不同_浅谈java的接口和C++虚类的相同和不同之处

    C++虚类相当于java中的抽象类,与接口的不同之处是: 1.一个子类只能继承一个抽象类(虚类),但能实现多个接口 2.一个抽象类可以有构造方法,接口没有构造方法 3.一个抽象类中的方法不一定是抽象方 ...

  7. java 抽象类,接口,object类详解

    抽象类: 如果一个类没有足够的信息去描绘一个具体的对象,那么这个类就可以叫做抽象类. 也可以叫做:可声明抽象方法的类==>抽象类 注意: <1>抽象类不可以实例化对象,所以它只能被继 ...

  8. abstract类_012 JAVA 抽象类、接口、String类的基础了解

    1.抽象方法和抽象类 抽象方法:使用abstract修饰的方法,没有方法体,只有声明.抽象方法可以当做是一种规范,让子类必须实现. 注意: 1.抽象方法没有方法体,只能以分号结尾 2.抽象方法只能声明 ...

  9. java定义一个door的类_再探Java抽象类与接口的设计理念差异

    原文:http://blog.csdn.net/sunboard/article/details/3831823 1.概述 一个软件设计的好坏,我想很大程度上取决于它的整体架构,而这个整体架构其实就是 ...

  10. Java程序设计当中包的使用_【学习笔记】 唐大仕—Java程序设计 第4讲 类、包和接口之4.2 类的继承...

    [学习笔记] 唐大仕-Java程序设计 第4讲 类.包和接口之4.2 类的继承 super的使用 1.使用super访问父类的域和方法 注意:正是由于继承,使用this可以访问父类的域和方法.但是有时 ...

最新文章

  1. 报文解析_104规约报文结构解析
  2. Android下的junit 单元测试
  3. iframe高度自适应,终于解决了
  4. 常见错误Delegate already added to touch dispatcher.的解决方案
  5. 计算机装机比赛感想,装机赛 篇一:一次雨露均沾的装机比赛
  6. 【C/C++】C/C++中Static的作用详述
  7. FIO压测-SSDvsHDD
  8. i9-10900K比9900K性能提升了多少?i9-10900K和i9-9900K区别对比评测
  9. x内存满白苹果解决_苹果x出现白苹果的现象及解决办法
  10. 北京服务器托管的必要性浅析
  11. 巧用python求解逻辑题,特简单!
  12. RK3128-android5.1-wifi兼容
  13. jdbc操作数据库实现查询产品、增加产品库存量例子
  14. Java面试八股文界的“六边形战士”22年最强,不接受反驳!
  15. 摩托罗拉v8对讲机驱动软件_摩托罗拉A8对讲机_摩托罗拉A8对讲机写频软件2.0 官方中文版-PC下载网...
  16. python可以应用lbm_格子玻尔兹曼方法(LBM)python程序提速
  17. 刚开始看英文文献,想问一下各位,最初应该怎么看进去?
  18. 电路理论基础学习笔记(2):chap1 电路元件与电路基本定律
  19. 云计算服务模型和openstack架构常用模块介绍
  20. 云体系联盟亮相中国互联网大会,推动产业融合创新

热门文章

  1. 【Android组件化】app壳工程
  2. Resilient Distributed Datasets (RDD)
  3. 关于学习linux的一些心得体会
  4. python 最小二乘法 线性方程组_Python实现基于最小二乘法的线性回归
  5. 扫码转账提示已停止访问该网页解决办法
  6. 微信防封养号规则大全(最新整理)
  7. html5中u1和li是什么意思,三年级下册英语U1 In class第1-5课时教案
  8. 【Fusion360】常用快捷键和技巧
  9. 1秒破解iPhone 13 Pro:可任意获取并删除设备上的数据
  10. Bazel构建系统的使用以及go项目实践案例