码迷,mamicode.com
首页 > 其他好文 > 详细

哈希小demo hashCode取模

时间:2014-08-07 09:48:19      阅读:367      评论:0      收藏:0      [点我收藏+]

标签:blog   java   os   io   for   2014   art   ar   

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取模

标签:blog   java   os   io   for   2014   art   ar   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!