【容器集合】set集合基础练习

本文详细介绍了Java集合框架中的Set接口,包括其无序、不重复的特点,以及HashSet和TreeSet的底层实现和特性。示例展示了如何使用HashSet和LinkedHashSet存储并遍历字符串数据,以及如何在List中去除重复元素。此外,还讨论了如何通过Comparable和Comparator接口对数据进行排序。
摘要由CSDN通过智能技术生成

知识点

set集合基础,练习练习


1.请说明set接口的特点?

  • 元素存取无序

  • 没有索引、只能通过迭代器或增强for循环遍历

  • 不能存储重复元素

2.set接口的实现类有哪些?他们的底层实现是什么?分别有什么特点?

HashXxx:底层借助了“哈希表”的数据结构;默认不支持排序

TreeXxx:底层借助了“红黑树”的数据结构;默认支持排序

HashSet集合的特点

  • 底层数据结构是哈希表

  • 对集合的迭代顺序不作任何保证,也就是说不保证存储和取出的元素顺序一致

  • 没有带索引的方法,所以不能使用普通for循环遍历

  • 由于是Set集合,所以是不包含重复元素的集合

TreeSet集合特点

  • 元素有序,可以按照一定的规则进行排序,具体排序方式取决于构造方法

    • TreeSet():根据其元素的自然排序进行排序

    • TreeSet(Comparator comparator) :根据指定的比较器进行排序

  • 没有带索引的方法,所以不能使用普通for循环遍历

  • 由于是Set集合,所以不包含重复元素的集合

3.TreeSet的排序方式有哪两种?

  • TreeSet():根据其元素的自然排序进行排序

  • TreeSet(Comparator comparator) :根据指定的比较器进行排序

4.请将如下4个字符串数据["aaa","bbb","ccc","ddd"],依次添加到HashSet集合中,并遍历查看存储结果。(使用增强for循环遍历)

import java.util.*;
public class Demo1 {
    public static void main(String[] args) {
     //创建集合对象
        HashSet <String> hs=new HashSet<String>();
           //添加元素
        hs.add("aaa");
        hs.add("bbb");
        hs.add("ccc");
        hs.add("ddd");
         //遍历
        for (String s:hs){
        System.out.println(s);
         //System.out.println(hs);
        }
    }

5.在List集合内去除重复数字值,要求尽量简单(可借助其他集合!!)

import java.util.*;
public class Demo1 {
    public static void main(String[] args) {
    //创建集合对象
       List<Integer> list = new ArrayList<Integer>();
        //添加元素
       list.add(1);
       list.add(2);
       list.add(1);
       list.add(3);
       list.add(1);
       //利用set表特性进行去重
       Set<Integer> set =new HashSet<>();
       set.addAll(list);
       //创建新集合用来保存去重后结果
        List<Integer> list1 = new ArrayList<Integer>();
        list1.addAll(set);
        System.out.println("去重后数组为"+list1);
    }
}

6.2019年1月份的世界编程语言排行榜从高到低依次如下: Java、C、Python、C++、Visual Basic .NET、JavaScript... 请将以上语言名称作为字符串元素,按顺序存入set集合中,并遍历查看。要求存储和遍历的顺序保持一致。

import java.util.*;
/*
2019年1月份的世界编程语言排行榜从高到低依次如下:
Java、C、Python、C++、Visual Basic .NET、JavaScript...
请将以上语言名称作为字符串元素,按顺序存入set集合中,并遍历查看。
要求存储和遍历的顺序保持一致。
 */
public class Demo1 {
    public static void main(String[] args) {
        //创建集合对象
        LinkedHashSet<String> hs = new LinkedHashSet<>();
        //添加元素
        hs.add("Java");
        hs.add("C");
        hs.add("Python");
        hs.add("C++");
        hs.add("Visual Basic .NET");
        hs.add("JavaScript");
        hs.add("...");
        //遍历
        for (String s : hs) {
            System.out.println(s+"   ");
            //System.out.println(hs)
        }
    }
}

7.现有若干图书信息(包含名称title、作者author、定价price)需要存储到set集合中,保证集合中无重复元素,并遍历查看。可以认为所有信息都相同的图书为重复数据。

import java.util.*;

public class Demo1 {
    public static void main(String[] args) {
        //创建集合对象
       HashSet<Book> hs = new HashSet<>();
        //添加元素
        hs.add(new Book("java","张三",39.0));
        hs.add(new Book("c","张三",32.0));
        hs.add(new Book("java","张三",39.0));
        hs.add(new Book("java","li",39.0));
        hs.add(new Book("ni","ls",39.0));
        hs.add(new Book("java","张三",39.0));
​
        //遍历
        for (Book book : hs) {
            System.out.println(book+"   ");
            //System.out.println(hs)
        }
    }
}
public class Book {
    private String title;
    private String author;
    private double price;
​
    public Book() {
    }
​
    public Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }
​
    public String getTitle() {
        return title;
    }
​
    public void setTitle(String title) {
        this.title = title;
    }
​
    public String getAuthor() {
        return author;
    }
​
    public void setAuthor(String author) {
        this.author = author;
    }
​
    public double getPrice() {
        return price;
    }
​
    public void setPrice(double price) {
        this.price = price;
    }
​
    @Override
    public String toString() {
        return "Book{" +
                "title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
​
    @Override
    public boolean equals(Object o) {
// 首先判断传进来的o是否是调用equals方法对象的this本身,提高判断效率
   if (o==this){return true;}
// 判断传进来的o是否是null,提高判断效率
   if (o==null){return false;}
    判断传进来的o是否是Book对象,防止出现类型转换的异常
   if (o instanceof Book){
       Book book =(Book) o;
       boolean flag=this.title.equals(book.title)&&this.price==book.price&&this.author.equals(book.author);
       return flag;
   }
// 如果没有走类型判断语句说明两个比较的对象它们的类型都不一样,结果就是false了
   return false;
   }
​
    @Override
    public int hashCode() {
//        result = 31 *result + (对象 !=null ?对象.hashCode() : 0);
//        result = 31 *result + 基本数值类型;(int)
//        result=31*result+(int)(Double.doubleToLongBits(x));强制转换为int类型
//        result = 31 *result + (布尔变量?1:0);
        int result=title.hashCode();
        result = 31*result+author.hashCode();
        result=31*result+(int)(Double.doubleToLongBits(price));
        return result;
    }
​
}

8.在某次考试中,学生的成绩信息如下(公有属性): 姓名(String) 年龄(int) 成绩(int): Tom 20 90; Jerry 22 95; John 20 100; Lily 22 100 ;Lucy 22 90; Kevin 22 90 请分别用Comparable和Comparator两个接口对以上同学的成绩做降序排序,如果成绩一样,那在成绩排序的基础上按照年龄由小到大排序,成绩和年龄都一样,则按照姓名的字典顺序排序。

import java.awt.print.Book;
import java.util.*;

public class Demo1 {
    public static void main(String[] args) {
        //创建集合对象
     List <Student> c=new ArrayList<>();
        //添加元素
     c.add(new Student("Tom",20,90));
     c.add(new Student("Jerry",22,95));
     c.add(new Student("John",20,100));
     c.add(new Student("Lily",22,90));
     c.add(new Student("Lucy",22,90));
     c.add(new Student("Kevin",22,90));
     //比较
        Collections.sort(c);
//        System.out.println(c);
        //遍历
        for (Student s : c) {
            System.out.println(s+"   ");
            //System.out.println(hs)
        }
       System.out.println("==========================");
        //外部比较器
        Collections.sort(c,new Compare());
        //遍历
        for (Student s : c) {
            System.out.println(s+"   ");
            //System.out.println(hs)
        }  
    }
}
import java.util.Objects;
​
public class Student implements Comparable{
String name;
int age;
int Score;
public Student(){}
​
    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        Score = score;
    }
​
    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 int getScore() {
        return Score;
    }
​
    public void setScore(int score) {
        Score = score;
    }
​
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", Score=" + Score +
                '}';
    }
​
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Score == student.Score &&
                Objects.equals(name, student.name);
    }
​
    @Override
    public int hashCode() {
        return Objects.hash(name, age, Score);
    }
​
    @Override
    public int compareTo(Object o) {
      Student inputStudent =(Student) o;
      //成绩降序
      int result=this.Score<inputStudent.Score?1 :(this.Score==inputStudent.Score?0:-1);
      //年龄升序
      if (result==0){
             result=this.age>inputStudent.age?1 :(this.age ==inputStudent.age?0:-1);
          if (result==0){
              result=this.name.compareTo(inputStudent.name);
          }
      }
​
​
      return result;
    }
}
import java.util.Comparator;
​
public class Compare implements Comparator {
​
    @Override
    public int compare(Object o1, Object o2) {
        Student student =(Student)o1;
        Student inputStudent =(Student) o2;
        //成绩降序
        int result=((Student) o1).Score<inputStudent.Score?1 :(((Student) o1).Score==inputStudent.Score?0:-1);
        //年龄升序
        if (result==0){
            result=((Student) o1).age>inputStudent.age?1 :(((Student) o1).age ==inputStudent.age?0:-1);
            if (result==0){
                result=((Student) o1).name.compareTo(inputStudent.name);
            }
        }
        return result;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值