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

来源:互联网 发布:ubuntu cpuz 编辑:程序博客网 时间:2024/05/29 16:04

需要继承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;@Overridepublic boolean equals(Object obj) {Category category = (Category)obj;return (this.categoryId==category.categoryId&& this.categoryName.equals(category.categoryName));}@Overridepublic 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;}}}


2 0
原创粉丝点击