首页 > 其他分享 >Day06集合-Set

Day06集合-Set

时间:2022-08-26 19:35:34浏览次数:141  
标签:Set name age Day06 System Person student 集合 println

Set接口

1.概述

  • 无序,五下标,元素不可重复

2. Set接口使用

/**
 * set接口使用(同collection)
 */
public class setDemo {
    public static void main(String[] args) {
        //创建set对象
        Set<String> idol = new HashSet<>();

        //1.添加
        System.out.println("---------1.添加----------");
        idol.add("zmy");
        idol.add("pjh");
        idol.add("ssw");
        idol.add("syq");
        System.out.println(idol);//输出时元素无序

        //2.删除
        System.out.println("---------2.删除----------");
        idol.remove("syq");
        System.out.println(idol);

        //3.遍历
        //3.1使用增强for
        System.out.println("-------3.1使用增强for------");
        for (String s:idol
             ) {
            System.out.println(s);
        }

        //3.2使用迭代器
        System.out.println("-------3.2使用迭代器------");
        Iterator<String> it = idol.iterator();
        while (it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }
    }
}

//输出结果:
---------1.添加----------
[ssw, zmy, syq, pjh]
---------2.删除----------
[ssw, zmy, pjh]
-------3.1使用增强for------
ssw
zmy
pjh
-------3.2使用迭代器------
ssw
zmy
pjh

3. HashSet

HashSet介绍
  • 基于HashCode计算元素存放位置
  • 当存入元素的哈希码相同时,会先调用equals方法进行确认,如果为true,则拒绝后者存入
HashSet使用
/**
 * hashset的使用
 * 底层数据结构:哈希表(数组+链表+红黑树)
 * 数据插入删除:
 * (1)先根据hashcode计算保存的位置,如果此位置为空则直接插入,如果不为空则执行(2)
 * (2) 执行equals方法,若equals方法返回为true则认为是重复元素,false则为新元素插入链表
 */
public class hashSet {
    public static void main(String[] args) {
        HashSet<student> hashSet = new HashSet<>();
        student s1 = new student("zhangsan",10);
        student s2 = new student("lisi",10);
        student s3 = new student("wangwu",11);
        student s4 = new student("zhaoliu",32);

        //1.添加
        hashSet.add(s1);
        hashSet.add(s2);
        hashSet.add(s3);
        hashSet.add(s4);

        //2.删除
        System.out.println("------------2.删除-------------");
        hashSet.remove(s4);
        /**
         * hashSet.remove(new student("zhangsan",10));
         * 该删除方法需要重写hashcode和equals方法
         */
        hashSet.remove(new student("zhangsan",10));
        System.out.println(hashSet);

        //3.遍历
        //3.1.使用迭代器遍历
        System.out.println("-------3.1.使用迭代器遍历---------");
        Iterator<student> it = hashSet.iterator();
        while (it.hasNext()){
            student s = it.next();
            System.out.println(s);
        }
        //3.2增强for
        System.out.println("----------3.2增强for------------");
        for (student s:hashSet
             ) {
            System.out.println(s);
        }

        //4.判断
        System.out.println("-------------4.判断----------");
        System.out.println(hashSet.isEmpty());
        System.out.println(hashSet.contains(s1));
    }
}


/**
重写的hashCode和equals方法
*/
@Override
   public boolean equals(Object o) {
       if (this == o) return true;
       if (o == null || getClass() != o.getClass()) return false;
       student student = (student) o;
       if (this.age == student.age && this.name == student.name) return true;
       return false;
   }
@Override
   public int hashCode() {
       int age = this.age + 31;
       int name = this.name.hashCode();
       return name + age;
   }

//输出结果
------------2.删除-------------
[student{name='wangwu', age=11}, student{name='lisi', age=10}]
-------3.1.使用迭代器遍历---------
student{name='wangwu', age=11}
student{name='lisi', age=10}
----------3.2增强for------------
student{name='wangwu', age=11}
student{name='lisi', age=10}
-------------4.判断----------
false
false
补充:idea重写的hashCode方法:
  • 使用31的原因:(1)31是一个质数,可以减少散列冲突的发生(2)提高执行效率:31 * i = (i << 5) - i
/**
 * 使用31的原因:
 * (1)31是一个质数,可以减少散列冲突的发生
 * (2)提高执行效率:31 * i = (i << 5) - i
 * @return
 */
@Override
public int hashCode() {
    int age = this.age + 31;
    int name = this.name.hashCode();
    return name + age;
}

4.TreeSet

TreeSet概述
  • 基于排序顺序实现元素不重复
  • 实现了sortedSet接口,对集合元素自动排序
  • 元素对象的类型必须实现Comparable接口,指定排序规则
  • 使用compareTo方法判断元素是否重复
TreeSet使用
/**
 * TreeSet的使用1
 * 数据结构:红黑树(二叉排序树)
 * 要求:元素必须实现Comparable接口,compareTo方法返回值为0,则认为是重复元素。
 */
public class treeSet {
    public static void main(String[] args) {
        //创建对象
        TreeSet<Person> tree = new TreeSet<>();
        Person p1 = new Person("cc",10);
        Person p2 = new Person("bb",10);
        Person p3 = new Person("aa",10);
        Person p4 = new Person("cc",9);

        //1.添加
        tree.add(p1);
        tree.add(p2);
        tree.add(p3);
        tree.add(p4);
        System.out.println(tree);

        //2.删除
        /**
         *tree.remove(new Person("aa",10));
         *可以直接删除,根据重写的compareTo方法判重。
         */
        tree.remove(new Person("aa",10));
        System.out.println(tree);

        //3.遍历
        //3.1迭代器
        Iterator<Person> it = tree.iterator();
        while (it.hasNext()){
            Person p = it.next();
            System.out.println(p);
        }
        //3.2增强for
        for (Person p:tree
             ) {
            System.out.println(p);
        }
    }
}

/**
*重写的comparaTo方法
*/

//比较规则:先比姓名,姓名相同比年龄。
 @Override
  public int compareTo(Person o) {
      int name = this.name.compareTo(o.name);
      int age = this.age - o.age;
      return name == 0 ? age : name;
  }

//输出结果:
[Person{name='aa', age=10}, Person{name='bb', age=10}, Person{name='cc', age=9}, Person{name='cc', age=10}]
[Person{name='bb', age=10}, Person{name='cc', age=9}, Person{name='cc', age=10}]
Person{name='bb', age=10}
Person{name='cc', age=9}
Person{name='cc', age=10}
Person{name='bb', age=10}
Person{name='cc', age=9}
Person{name='cc', age=10}
/**
 * TreeSet使用2
 * comparator结口:定制比较规则(比较器)
 * 继承comparator结口则不必重写compareTo方法
 */
public class treeSetComparator {
    public static void main(String[] args) {
        //1创建对象,继承接口
        //1.1使用匿名内部类new Comparator<Person>()
        TreeSet<Person> treeSet = new TreeSet<>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int name = o1.getName().compareTo(o2.getName());
                int age = o1.getAge() - o2.getAge();
                return name == 0 ? age : name;
            }
        });
        
        //1.2使用正则表达式
        TreeSet<Person> treeSet1 = new TreeSet<>((o1, o2) -> {
            int name = o1.getName().compareTo(o2.getName());
            int age = o1.getAge() - o2.getAge();
            return name == 0 ? age : name;
        });
    }
}
TreeSet案例
/**
 * 一个TreeSet案例
 * 将字符按照长度排序,长度相同的按照字典表排序
 * 使用Comparator接口
 */
public class treeSetExample {
    public static void main(String[] args) {
        TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int length = o1.length() - o2.length();
                int string = o1.compareTo(o2);
                return length == 0 ? string : length;
            }
        });

        treeSet.add("a");
        treeSet.add("bb");
        treeSet.add("ccc");
        treeSet.add("ee");
        treeSet.add("ddd");
        treeSet.add("b");
        treeSet.add("eee");

        System.out.println(treeSet.toString());
    }
}

//结果输出:
[a, b, bb, ee, ccc, ddd, eee]

标签:Set,name,age,Day06,System,Person,student,集合,println
From: https://www.cnblogs.com/workplace-blog/p/16628957.html

相关文章

  • Day06-泛型
    泛型1.泛型介绍泛型是JDK1.5引入的新特性,本质是参数化类型,把类型作为参数传递常见形式有:泛型类,泛型接口,泛型方法语法:<T,....>:T称为类型占位符,表示一种引用数据......
  • Day07集合-HashMap
    HashMap特点:jdk1.2,运行效率快,线程不安全,允许null作为key或者value使用:存储结构:哈希表(数组+链表+红黑树)使用key的hashcode和equals判重//创建HashMap<student,St......
  • Day07集合-Map父接口
    MapMap父接口存储一对数据(key—Value),无序,无下标,建不可以重复,值可以重复。方法方法摘要voidclear()从此映射中移除所有映射关系(可选操作)。bo......
  • Day05集合-Collection
    集合1.集合的概念对象的容器,实现了对对象的常用操作,类似数组功能位置:java.util.*2.集合和数组的区别集合长度不固定,数组长度固定集合只能存储引用数据类型,数组可......
  • “X-Content-Type-Options”头缺失或不安全,添加Filter后 hsresponse.setHeader("X-Con
    AppScan扫描出的问题:  问题修复,添加Filter: 问题修复后,列表出不来: ......
  • url not set
    UrInotset原因与处理方法今天下午跑代码时发现,上午能跑的代码下午跑不了了。一直报Urlnotset错误。出现这个问题的主要原因,是因为代码中的@ConfigurationProperti......
  • C#集合:ICollection和IList接口
    虽然枚举接口IEnumerable提供了一种向前迭代集合的协议,但是它们并没有提供确定集合大小、根据索引访问成员、搜索以及修改集合的机制。为了实现这些功能,.NETCore定义了ICo......
  • 面试官:HashSet 的实现原理是怎样的?底层是什么数据结构?被问到了。。
    来源:https://www.cnblogs.com/LiaHon/p/11257805.html一.HashSet概述HashSet是Java集合Set的一个实现类,Set是一个接口,其实现类除HashSet之外,还有TreeSet,并继承了Collect......
  • 【Location Kit】定位服务设置时间间隔mLocationRequest.setInterval(15 * 1000)不起
    ​ 【问题描述】mLocationRequest.setInterval(5*1000);//设置5″  定位返回间隔10″mLocationRequest.setInterval(10*1000);//设置10″ 定位返回间隔10″......
  • 延时任务-基于redis zset的完整实现
    所谓的延时任务给大家举个例子:你买了一张火车票,必须在30分钟之内付款,否则该订单被自动取消。订单30分钟不付款自动取消,这个任务就是一个延时任务。 我之前已经写过2篇关于......