码迷,mamicode.com
首页 > 编程语言 > 详细

Java 将自己定义的对象作为HashMap的key

时间:2014-10-07 17:44:23      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:ar   java   div   art   c   on   r   amp   new   

须要继承Map的equals函数和hashCode函数

package com.category;

import java.util.HashMap;

public class GenCategoryLevelData {

	private static HashMap<Category, Integer> categoryLevel = new HashMap<Category, Integer>();
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 分类
	 * @author ouyangyewei
	 *
	 */
	public static class Category {
		public long categoryId;
		public String categoryName;
		
		@Override
		public boolean equals(Object obj) {
			Category category = (Category)obj;
			return (this.categoryId==category.categoryId
					&& this.categoryName.equals(category.categoryName));
		}
		@Override
		public final int hashCode() {
            int hashCode = 17;
            hashCode = hashCode * 31 + 1;
            hashCode = hashCode * 31 + 1;
            return hashCode;
        }
		
		public Category() {
			// empty
		}
		public Category(long categoryId, String categoryName) {
			this.categoryId = categoryId;
			this.categoryName = categoryName;
		}
		public long getCategoryId() {
			return categoryId;
		}
		public void setCategoryId(long categoryId) {
			this.categoryId = categoryId;
		}
		public String getCategoryName() {
			return categoryName;
		}
		public void setCategoryName(String categoryName) {
			this.categoryName = categoryName;
		}
	}
}


Java 将自己定义的对象作为HashMap的key

标签:ar   java   div   art   c   on   r   amp   new   

原文地址:http://www.cnblogs.com/zfyouxi/p/4009465.html

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