使用自定义的类作为Map接口key的参数时

来源:互联网 发布:fps游戏鼠标推荐 知乎 编辑:程序博客网 时间:2024/06/05 10:49
package com.jluzh.map;import java.util.Hashtable;import java.util.Map;/** * 关于Map集合中key的说明 * 需要覆写Object的hashCode()方法和equals()方法 * @className MapTestKey.java * @author jluzh 04140717 * @date 2017年3月24日 * @effect: */class Book{    private String title;    public Book(String title) {        super();        this.title = title;    }    @Override    public String toString() {        return "Book [title=" + title + "]";    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + ((title == null) ? 0 : title.hashCode());        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Book other = (Book) obj;        if (title == null) {            if (other.title != null)                return false;        } else if (!title.equals(other.title))            return false;        return true;    }}public class MapTestKey {    public static void main(String[] args) {         Map<Book,String> map = new Hashtable<Book,String>();         map.put(new Book("java开发"), "JAVA");         System.out.println(map.get(new Book("java开发")));//需要覆写Object类中的hashCode()方法和equals()方法    }}
0 0
原创粉丝点击