栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

hashSet的创建和基本的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

hashSet的创建和基本的使用

package com.itheima2;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

public class HashSetDemo {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	// 使用hashSet创建的集合数据可以重复
	// 使用set创建的集合数据可以重复
	// **把**操作的对象类重写eqauls方法 和重写hashCode方法则可以去重****
	// 创建集合对象
	HashSet hs = new HashSet();
	// 创建学生对象
	Student s = new Student("宋东雄", 12);
	Student s1 = new Student("宋东辉", 126);
	Student s2 = new Student("宋东辉", 126);
	// 添加元素对象
	hs.add(s1);
	hs.add(s);
	hs.add(s2);
	// foreach遍历元素
	for (Student object : hs) {
		System.out.println(object.getName() + "  " + object.getAge());
	}

	System.out.println("-------------------------");
	// 使用迭代器遍历元素
	Iterator it = hs.iterator();
	// it.hasNext()判断下一个是否为空
	while (it.hasNext()) {
		// it.next();获取下一个值
		Student student = (Student) it.next();
		System.out.println(student.getName() + "  " + student.getAge());
	}

	// 把集合装换为数组
	Object[] obj = hs.toArray();
	// 使用for循环遍历
	for (int i = 0; i < obj.length; i++) {
		Student ss = (Student) obj[i];
		System.out.println(ss);
	}
}

}

class Student {

String name;
int age;

public Student() {
	super();
	// TODO Auto-generated constructor stub
}

public Student(String name, int age) {
	super();
	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 String toString() {
	return "Student [name=" + name + ", age=" + age + "]";
}

@Override
public int hashCode() {
	return Objects.hash(age, name);
}

@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Student other = (Student) obj;
	return age == other.age && Objects.equals(name, other.name);
}

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/756121.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号