package HashMap;
public class LinkedList {
private Node head;
private int linkedSize;
public LinkedList(){
this.head=null;
linkedSize=0;
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public int getLinkedSize() {
return linkedSize;
}
public void setLinkedSize(int linkedSize) {
this.linkedSize = linkedSize;
}
static class Node{
private Student stu;
private Node next;
public Node() {
}
public Node(Student stu, Node next) {
this.stu=stu;
this.next = next;
}
@Override
public String toString() {
return "[stu=" + stu + "]==>";
}
}
public void add(Student stu){
if(head==null){
head=new Node(stu,null);
linkedSize++;
return;
}
Node node=head;
while(node.next!=null){
node=node.next;
}
node.next=new Node(stu,null);
linkedSize++;
return;
}
public void list(){
if(this.linkedSize==0){
return;
}
else{
Node node=head;
while(node.next!=null){
System.out.print(node);
node=node.next;
}
System.out.print(node);
}
}
}
package HashMap;
public class MyHashMap {
private int size=8;
LinkedList[] arr;
public MyHashMap(){
arr=new LinkedList[size];
for(int i=0;i<arr.length;i++){
arr[i]=new LinkedList();
}
}
public MyHashMap(int size){
this.size=size;
arr=new LinkedList[size];
for(int i=0;i<arr.length;i++){
arr[i]=new LinkedList();
}
}
public int hash(Student stu){
return stu.getId()%this.size;
}
public void put(Student stu){
if(stu==null){
return ;
}
int index=hash(stu);
arr[index].add(stu);
}
public void listMap(){
for(int i=0;i<8;i++){
if(arr[i].getLinkedSize()==0){
System.out.println("第"+(i+1)+"条链表为空");
}
else{
System.out.print("第"+(i+1)+"条链表:");
arr[i].list();
System.out.println();
}
}
}
}
package HashMap;
public class Student {
private Integer id;
private String name;
public Student(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package HashMap;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Student stu=new Student(23,"zhangsan");
Student stu1=new Student(24,"lisi");
Student stu2=new Student(25,"wangwu");
Student stu3=new Student(26,"zhaoliu");
Student stu4=new Student(8,"xiaoba");
MyHashMap map=new MyHashMap();
map.put(stu);
map.put(stu1);
map.put(stu2);
map.put(stu3);
map.put(stu4);
map.listMap();
}
}
测试结果