package demo13;
public class StuInfo {
private int age;
private int count;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* 散列函数
*/
public int hashCode() {
return age;
}
public StuInfo(int age, int count) {
super();
this.age = age;
this.count = count;
}
public StuInfo(int age) {
super();
this.age = age;
}
@Override
public String toString() {
return "StuInfo [age=" + age + ", count=" + count + "]";
}
}
package demo13;
import java.util.Arrays;
public class HashTable {
private StuInfo[] data = new StuInfo[100];
/**
* 向散列表中添加元素
* @param stuInfo
*/
public void put(StuInfo stuInfo) {
//调用散列函数获取存储位置
int index = stuInfo.hashCode();
//添加元素
data[index]=stuInfo;
}
public StuInfo get(StuInfo stuInfo) {
return data[stuInfo.hashCode()];
}
@Override
public String toString() {
return "HashTable [data=" + Arrays.toString(data) + "]";
}
}
package demo13;
import java.util.Arrays;
public class TestHashTable {
public static void main(String[] args) {
StuInfo s1 = new StuInfo(16, 3);
StuInfo s2 = new StuInfo(17, 11);
StuInfo s3 = new StuInfo(18, 23);
StuInfo s4 = new StuInfo(19, 24);
StuInfo s5 = new StuInfo(20, 9);
HashTable ht = new HashTable();
ht.put(s1);
ht.put(s2);
ht.put(s3);
ht.put(s4);
ht.put(s5);
System.out.println(ht);
//想要获取的目标数据
StuInfo target = new StuInfo(18);
StuInfo info = ht.get(target);
System.out.println(info);
}
}