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()方法
}
}
使用自定义的类作为Map接口key的参数时
最新推荐文章于 2024-01-31 09:59:33 发布