- package com.itheima.test;
- import java.util.HashSet;
- import java.util.Iterator;
- public class HashCodeTest {
- public static void main(String[] args) {
- HashSet<OtherPerson> hashSet = new HashSet<OtherPerson>();
- hashSet.add(new OtherPerson("Avici", 25));
- hashSet.add(new OtherPerson("Jack", 38));
- hashSet.add(new OtherPerson("Rose", 32));
- hashSet.add(new OtherPerson("Lily", 17));
- hashSet.add(new OtherPerson("Lucy", 16));
-
- Iterator<OtherPerson> iterator = hashSet.iterator();
- while(iterator.hasNext()) {
- println(iterator.next());
- }
- }
- public static void println(Object obj) {
- System.out.println(obj);
- }
- }
- class OtherPerson {
- private String name = null;
- private int age = 0;
-
- public OtherPerson(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + age;
- return result;
- }
-
- @Override
- public String toString() {
- return "Person [name=" + name + ", age=" + age + "]";
- }
- }
复制代码 HashSet存储元素是将其按HashCode值放入桶中把?如何重写其方法让它将元素按照age大小顺序存进去,那么我就可以取出年龄有序的元素。
此时打印结果为:- Person [name=Jack, age=38]
- Person [name=Lily, age=17]
- Person [name=Avici, age=25]
- Person [name=Rose, age=32]
- Person [name=Lucy, age=16]
复制代码 乱序啊。如何改进hashCode()方法???- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + age;
- return result;
- }
复制代码 |