1.自定义人类,包含姓名和年龄属性。
创建4个人存储到HashSet中,如果姓名和年龄相同的人看做同一人不存储
1条回答 默认 最新
- a5156520 2022-07-18 14:29关注
import java.util.HashSet; public class Person { public String name; public int age; public static void main(String[] args) { // TODO Auto-generated method stub Person p1 = new Person("张三",23); Person p2 = new Person("张三",24); Person p3 = new Person("张三",23); Person p4 = new Person("李四",23); HashSet pset = new HashSet(); add(pset,p1); add(pset,p2); add(pset,p3); add(pset,p4); System.out.println("HashSet中存储的Person对象如下:"); for(Object obj:pset) { Person p = (Person)obj; System.out.println(p); } } //https://blog.csdn.net/qq_41562587/article/details/103893416 public static void add(HashSet pset,Person p) { int find=0; for(Object obj:pset) { Person tp = (Person)obj; if(tp.equals(p)) { find=1; break; } } if(find==0) { pset.add(p); System.out.println("添加Person对象"+p+"成功!"); }else { System.out.println("HashSet中存在此对象,添加Person对象"+p+"失败!"); } } 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; } public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person() { super(); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } public boolean equals(Person p) { if(this.getAge()==p.getAge()&&this.getName().equals(p.getName())) { return true; }else { return false; } } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报