JAVA_HashSet

package com.kk.Collection;

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

public class HashSetTest {
public static void main(String[] args) {
Set hashSet=new HashSet();
hashSet.add(new Student(0,"kk"));
hashSet.add(new Student(1,"mm"));
hashSet.add(new Student(1,"mm"));//内存地址和值一样,Set将不会添加同样的对象
Iterator it=hashSet.iterator();
while(it.hasNext()){
Student stu=(Student) it.next();
System.out.println(stu.name);
}
}

static class Student {
int num;

String name;

public Student(int num, String name) {
this.num = num;
this.name = name;
}

@Override
/**
* 判断对象的内存地址是否一样
*/
public int hashCode() {
return num*name.hashCode();
}

@Override
/**
* 判断对象的值是否一样
*/
public boolean equals(Object obj) {
Student stu=(Student) obj;
return this.num==stu.num && this.name.equals(stu.name);
}
}
}
原文地址:https://www.cnblogs.com/BigIdiot/p/2284966.html