|
锁定老贴子 主题:这个题真实变态 怎么改呐!!!
该帖已经被评为新手帖
|
|
|---|---|
| 作者 | 正文 |
|
最后更新时间:2007-05-10
/**补充完该类,不修改main方法,使得get()方法可以取到值*/
package test; import java.util.HashMap; import java.util.Map; public class StudentTest { private static final class Student { private static String name; public Student(String name) { this.name = name; } } public static void main(String[] args) { Map p = new HashMap(); p.put(new Student("lily"), "sister"); System.out.println(p.get("lily")); System.out.print(p.keySet().iterator().next()); } } 声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
SORRY! System.out.print(p.keySet().iterator().next()); 应该去掉
|
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
hashcode
|
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
请问能详细一点吗?
是重写Student类的hashCode()方法吗? |
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
hashCode(){
return name.hashCode(); } |
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
private static final class Student {
private static String name;
public Student(String name) {
this.name = name;
}
public int hashCode() {
return this.name.hashCode();
}
}
试了一下 Map p = new HashMap();
Student tt = new Student("lily");
p.put(tt, "sister");
System.out.println(p.get("lily"));
null Map p = new HashMap();
Student tt = new Student("lily");
p.put(("lily", "sister");
System.out.println(p.get("lily"));
sister why??????? |
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
if(!(obj instanceof Test)) return false;
大约map先作这件事
public Object get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry e = table[i];
while (true) {
if (e == null)
return e;
if (e.hash == hash && eq(k, e.key))
return e.value;
e = e.next;
}
}
static int hash(Object x) {
int h = x.hashCode();
h += ~(h << 9);
h ^= (h >>> 14);
h += (h << 4);
h ^= (h >>> 10);
return h;
}
|
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
翻了一下 没找到类似语句
public Object get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry e = table[i];
while (true) {
if (e == null)
return e;
if (e.hash == hash && eq(k, e.key))
return e.value;
e = e.next;
}
}
public Object put(Object key, Object value) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
if (e.hash == hash && eq(k, e.key)) {
Object oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, k, value, i);
return null;
}
刚开始怀疑是 indexFor 返回的不一样 可是test了一下 都是10 debug了一下 第一个情况 table里面是 Test$Student@32afca=sister 第二个情况 table里面是 lily=sister |
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
走到了 是这句
if (e.hash == hash && eq(k, e.key)) |
|
| 返回顶楼 | |
|
最后更新时间:2007-05-10
通过统一定义equals()和hashCode(), 可以提升类作为基于散列的集合中的关键字的使用性 怎样写这两个方法呐? |
|
| 返回顶楼 | |








