Set接口
概述
- 不包含重复元素的集合
- 数据无序,因为set集合没有下标
- 常用来给数据做去重处理
- 此类允许使用 null 元素。
特点
- HashSet:底层是哈希表,包装了HashMap,相当于向HashSet中存入数据时,会把数据作为K,存入内部的HashMap中。当然K仍然不许重复。
- TreeSet:底层就是TreeMap,也是红黑树的形式,便于查找数据。
- HashMap实现中,当哈希值相同的对象,会在同一个hash值的位置存储不同属性的数据。
常用方法
boolean add(E e):添加元素。
boolean addAll(Collection c):把小集合添加到大集合中 。
boolean contains(Object o) : 如果此 collection 包含指定的元素,则返回 true。
boolean isEmpty() :如果此 collection 没有元素,则返回 true。
Iterator<E> iterator():返回在此 collection 的元素上进行迭代的迭代器。
boolean remove(Object o) :从此 collection 中移除指定元素的单个实例。
int size() :返回此 collection 中的元素数。
Objec[] toArray():返回对象数组
测试方法
private static void set() {
Set set01 =new HashSet();
Set set02 =new HashSet();
set02.add("科比");
set02.add("奥尼尔");
set01.add(1);
set01.add("你好");
set01.add(1);
set01.add("hello");
System.out.println(set01.toString()); //不会重复
set01.addAll(set02);
System.out.println(set01); //将集合set02的所有元素加入到set01当中(数据无序)
System.out.println(set01.contains("科比")); //判断是否包含"科比"这个元素,返回布尔值
System.out.println(set01.isEmpty()); //判断集合是否为空
System.out.println(set01.toArray()); //返回地址值
//迭代
Iterator it =set01.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
HashSet接口
概述
- 此类实现 Set 接口,由哈希表(实际上是一个 HashMap 实例)支持。它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。此类允许使用 null 元素。
特点
- 同Set接口,略…
常用方法
- 同Set接口,略…
测试类
private static void hashSet() {
//1,创建对象
HashSet<Student> set = new HashSet<>();
//2,把Student对象存入set中
Student s1 = new Student("钟南山",84);
Student s2 = new Student("袁隆平",90);
Student s3 = new Student("李子柒",25);
Student s4 = new Student("刘沛霞",20);
Student s5 = new Student("刘沛霞",20);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
set.add(s5);
System.out.println(set);
System.out.println(s4.equals(s5));
System.out.println(s4.hashCode() +"=====" + s5.hashCode());
}
class Student {
String name;
int age;
//TODO 构造方法:右键-generate-construcor
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//TODO toString():右键-generate-toString()
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
//右键-generate-equals() and hashCode()
// key.equals(k) --让两个对象间的equals()返回true
// 默认是==比较两个对象间的地址值.需要按照属性值比较.--重写equals()
@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 &&
Objects.equals(name, student.name);
}
//重写hashCode()--目的是让底层运算hash值时别再new一次算一个
//而是,根据对象的属性值运算得到hash值,如果属性值一样,就计算出来相同的hash值
//重写了hashCode(),使得两个属性相同的对象拥有了相同的hash值!!
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
执行结果: