首页 > 代码库 > 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; } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。