首页 > 其他 > 详细

哈希小demo hashCode取模

时间:2014-08-07 09:48:19      阅读:1213      评论:0      收藏:0      [点我收藏+]
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);
		
		
	}

}
运行结果
638559109
1287160904
1710537297
636768290
1253637029
Person [username=c, age=14]
----------------------------------
Person [username=a, age=12]
----------------------------------
Person [username=b, age=13]
Person [username=d, age=15]
Person [username=e, age=16]
----------------------------------


哈希小demo hashCode取模,布布扣,bubuko.com

哈希小demo hashCode取模

原文:http://blog.csdn.net/simonchi/article/details/38412839

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!