workplace-blog

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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]
posted on 2022-08-26 19:27  多巴胺LLL  阅读(23)  评论(0)    收藏  举报