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

需要继承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,布布扣,bubuko.com

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

上一篇:JAVA正则表达式高级用法(分组与捕获)


下一篇:JavaScript Patterns 7.1 Singleton