首页 > 代码库 > 哈希小demo hashCode取模

哈希小demo hashCode取模

package demo;

import java.util.ArrayList;
import java.util.List;

class Person {
	private String username;
	private int age;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Person(String username, int age) {
		super();
		this.username = username;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + "]";
	}
	
}

public class Test {

	public static void printList(List list) {
		for(int i=0;i<list.size();i++) {
			System.out.println(list.get(i));
		}
		System.out.println("----------------------------------");
	}
	
	public static void main(String[] args) {
		int partition = 3;
		Person p1 = new Person("a",12);
		Person p2 = new Person("b",13);
		Person p3 = new Person("c",14);
		Person p4 = new Person("d",15);
		Person p5 = new Person("e",16);
		Person p[] = new Person[]{p1,p2,p3,p4,p5};
		List list0 = new ArrayList();
		List list1 = new ArrayList();
		List list2 = new ArrayList();
		for(int i=0;i<p.length;i++) {
			Person pi = p[i];
			int hash = pi.hashCode();
			System.out.println(hash);
			if(hash%partition==0) {
				list0.add(pi);
			}
			if(hash%partition==1) {
				list1.add(pi);
			}
			if(hash%partition==2) {
				list2.add(pi);
			}
		}
		printList(list0);
		printList(list1);
		printList(list2);
		
		
	}

}
运行结果
638559109128716090417105372976367682901253637029Person [username=c, age=14]----------------------------------Person [username=a, age=12]----------------------------------Person [username=b, age=13]Person [username=d, age=15]Person [username=e, age=16]----------------------------------