0
点赞
收藏
分享

微信扫一扫

Jetson Orin Nano nvme系统备份和恢复

乐百川 2023-06-04 阅读 78

文章目录



在这里插入图片描述

1. HashSet集合概述和特点

  • 底层数据结构是哈希表
  • 存取无序
  • 不可以存储重复元素
  • 没有索引,不能使用普通for循环遍历

2. HashSet集合的基本应用

存储字符串并遍历

public class HashSetDemo {
	public static void main(String[] args) {
		//创建集合对象
		HashSet<String> set = new HashSet<String>();
		//添加元素
		set.add("hello");
		set.add("world");
		set.add("java");
		//不包含重复元素的集合
		set.add("world");
		
		//遍历
		for(String s : set) {
			System.out.println(s);
		}
	}
}

3. 哈希值

  • 哈希值简介
    是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值
  • 如何获取哈希值
    Object类中的public int hashCode():返回对象的哈希码值
  • 哈希值的特点
    • 同一个对象多次调用hashCode()方法返回的哈希值是相同的
    • 默认情况下,不同对象的哈希值是不同的。而重写hashCode()方法,可以实现让不同对象的
      哈希值相同

4. HashSet集合存储学生对象并遍历【应用】

  • 案例需求
    创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合
    要求:学生对象的成员变量值相同,我们就认为是同一个对象

  • 代码实现

public class Student {
	private String name;
	private int age;
	
	public Student() {
	}
	
	public Student(String name, int age) {
		this.name = name;
		this.age = 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;
	}
	
	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
			Student student = (Student) o;
		if (age != student.age) return false;
			return name != null ? name.equals(student.name) : student.name ==
		null;
	}
	
	@Override
	public int hashCode() {
		int result = name != null ? name.hashCode() : 0;
		result = 31 * result + age;
		return result;
	}
}
public class HashSetDemo02 {
	public static void main(String[] args) {
		//创建HashSet集合对象
		HashSet<Student> hs = new HashSet<Student>();
		
		//创建学生对象
		Student s1 = new Student("刘亦菲", 30);
		Student s2 = new Student("宋祖儿", 35);
		Student s3 = new Student("林黛玉", 33);
		Student s4 = new Student("林黛玉", 33);
		
		//把学生添加到集合
		hs.add(s1);
		hs.add(s2);
		hs.add(s3);
		hs.add(s4);
		
		//遍历集合(增强for)
		for (Student s : hs) {
			System.out.println(s.getName() + "," + s.getAge());
		}
	}
}

总结
HashSet集合存储自定义类型元素,要想实现元素的唯一,要求必须重写自定义类型的hashCode
方法和equals方法


在这里插入图片描述

举报

相关推荐

0 条评论