首页 > 代码库 > Java 将自定义的对象作为HashMap的key

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;
		}
	}
}