- //练习,创建一个自定义类,将其对象加入hashset集合。
- import java.util.HashSet;
- import java.util.Iterator;
- public class testHashSet {
- public static void main(String[] agrs){
- HashSet hs = new HashSet<student>();
- hs.add(new student(11,"zhangsan"));
- hs.add(new student(2,"lisi"));
- hs.add(new student(33,"wangwu"));
- hs.add(new student(4,"zhangsan"));
-
- for(Iterator<student> i = hs.iterator();i.hasNext();){
- student p = i.next();
- System.out.println(p);
- }
- }
- }
- class student{
- private int age;
- private String name;
-
- student(int age,String name){
- this.name = name;
- this.age = age;
- }
-
- public String toString() {
- return "age=" + age + ", name=" + name;
- }
- public int hashCode(){
- return this.name.hashCode()+age*21;
- }
-
- public boolean equals(Object obj){
- if(obj instanceof student)
- throw new RuntimeException();
- student p = (student)obj;
- if(this.age == p.age && this.name.equals(p.name)){
- return true;
- }else{
- return false;
- }
- }
-
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
复制代码
|
|