原创

哈希小demo hashCode取模

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://xxlcube.blog.csdn.net/article/details/38412839
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]
----------------------------------


文章最后发布于: 2014-08-07 09:05:53
展开阅读全文
0 个人打赏
私信求帮助

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 酷酷鲨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览