首页 技术 正文
技术 2022年11月18日
0 收藏 999 点赞 4,618 浏览 1511 个字
import java.util.Set;
import java.util.HashSet;public class SetTest {
public static void main(String[] args) {
/*
*对于用户自己定义类型的数据放在容器(Set)中
*务必重写equals和hashCode方法
*要不然stu1和stu2放在容器中,和觉得是两个不同的元素
**///set中存放的元素是无序的
//set中存储的元素是不能够反复的(依据equals方法和hashCode方法推断)
Set set = new HashSet();
Student stu1 = new Student(1, "aaa");
Student stu2 = new Student(1, "aaa");
Student stu3 = new Student(2, "ccc");
Student stu4 = new Student(8, "fff");set.add(stu1);
set.add(stu2);
set.add(stu3);
set.add(stu4);System.out.println(set);
}
}class Student {
private int id;
private String name;public Student(int id, String name) {
this.id = id;
this.name = name;
}@Override
public String toString() {
return this.id + " " + this.name;
}@Override
public boolean equals(Object obj) {
Student stu = (Student) obj;return this.id == stu.id && this.name.equals(stu.name);
}@Override
public int hashCode() {
return this.id*this.name.hashCode();
}
}
输出结果:
[8 fff, 1 aaa, 2 ccc]

假设不重写hashCode和equals方法

import java.util.Set;
import java.util.HashSet;public class SetTest {
public static void main(String[] args) {
/*
*对于用户自己定义类型的数据放在容器(Set)中
*务必重写equals和hashCode方法
*要不然stu1和stu2放在容器中,和觉得是两个不同的元素
**///set中存放的元素是无序的
//set中存储的元素是不能够反复的(依据equals方法和hashCode方法推断)
Set set = new HashSet();
Student stu1 = new Student(1, "aaa");
Student stu2 = new Student(1, "aaa");
Student stu3 = new Student(2, "ccc");
Student stu4 = new Student(8, "fff");set.add(stu1);
set.add(stu2);
set.add(stu3);
set.add(stu4);System.out.println(set);
}
}class Student {
private int id;
private String name;public Student(int id, String name) {
this.id = id;
this.name = name;
}@Override
public String toString() {
return this.id + " " + this.name;
}
}
输出结果:
[1 aaa, 1 aaa, 8 fff, 2 ccc]

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,910
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,435
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,250
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,061
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,693
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,731