回到首页
个人中心
反馈问题
注册登录
下载APP
代码
提交代码
import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class HashSetDemo4 { /** * 静态内部类:慕课网学生 */ static class ImoocStudent { private String nickname; private String position; public ImoocStudent() { } public ImoocStudent(String nickname, String position) { this.setNickname(nickname); this.setPosition(position); } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @Override public String toString() { return "ImoocStudent{" + "nickname='" + nickname + '\'' + ", position='" + position + '\'' + '}'; } } public static void main(String[] args) { Set<ImoocStudent> hashSet = new HashSet<>(); // 实例化3个慕课网学生对象 ImoocStudent imoocStudent1 = new ImoocStudent("Colorful", "服务端工程师"); ImoocStudent imoocStudent2 = new ImoocStudent("Lillian", "客户端工程师"); ImoocStudent imoocStudent3 = new ImoocStudent("小慕", "架构师"); // 新增元素 hashSet.add(imoocStudent1); hashSet.add(imoocStudent2); hashSet.add(imoocStudent3); // 使用Iterator遍历hashSet Iterator<ImoocStudent> iterator = hashSet.iterator(); System.out.println("迭代器的遍历结果为:"); while (iterator.hasNext()) { System.out.println(iterator.next()); } // 查找并删除 if (hashSet.contains(imoocStudent1)) { hashSet.remove(imoocStudent1); } System.out.println("删除nickname为Colorful的对象后,集合元素为:"); System.out.println(hashSet); } }
运行结果