如何实现HashMap的get()方法重写? 如题~~~~各位大大能否给个例子不一定是hashMap的,其他的也行。我就想知道实现方法。谢谢 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 敢问LZ,重写get方法有何含义?我用过的重写HashCode.import java.util.*; public class Exp2 { public static void main(String[] args){ HashMap h2=new HashMap(); for(int i=0;i<10;i++) h2.put(new Element(i), new Figureout()); System.out.println("h2:"); System.out.println("Get the result for Element:"); Element test=new Element(5); if(h2.containsKey(test)) System.out.println((Figureout)h2.get(test)); else System.out.println("Not found"); }}class Element{ int number; public Element(int n){ number=n; } }class Figureout{ Random r=new Random(); boolean possible=r.nextDouble()>0.5; public String toString(){ if(possible) return "OK!"; else return "Impossible!"; }}某位大侠博客摘言:1.不必对每个不同的对象都产生一个唯一的hashcode,只要你的HashCode方法使get()能够得到put()放进去的内容就可以了。即“不为一原则”。 2.生成hashcode的算法尽量使hashcode的值分散一些,不要很多hashcode都集中在一个范围内,这样有利于提高HashMap的性能。即“分散原则”。 因为在get()方法中,key不存在的话,会抛空指针而我现在的需求是,如果get不到值,则作其他处理。因为代码里大量用到get()方法,不可能一个一个try()。所以想重写 public class MyHashMap extends HashMap { @Override public Object get(Object key) { try { return super.get(key); } catch (Exception e) { return ""; } }} 请教一个简单多线程问题! 数据结构推荐本书? java如何操作postscript文件 请问如何将一个图片或一个Frame窗口添加到JPanel上 abstract class和interface的区别在哪里? [非灌水]哪位兄弟知道如何制作背景透明gif? 有没有对jsp托管主机有兴趣的朋友? 大家觉得 数据结构和算法 的相关知识对学java重要吗 这是怎么回事? ************在JAVA中发个声音好难啊,各位帮帮忙 求:JSP页面中下拉框的代码 Jacob 操作Excel的问题???
import java.util.*;
public class Exp2 {
public static void main(String[] args){
HashMap h2=new HashMap();
for(int i=0;i<10;i++)
h2.put(new Element(i), new Figureout());
System.out.println("h2:");
System.out.println("Get the result for Element:");
Element test=new Element(5);
if(h2.containsKey(test))
System.out.println((Figureout)h2.get(test));
else
System.out.println("Not found");
}
}class Element{
int number;
public Element(int n){
number=n;
}
}class Figureout{
Random r=new Random();
boolean possible=r.nextDouble()>0.5;
public String toString(){
if(possible)
return "OK!";
else
return "Impossible!";
}
}某位大侠博客摘言:
1.不必对每个不同的对象都产生一个唯一的hashcode,只要你的HashCode方法使get()能够得到put()放进去的内容就可以了。即“不为一原则”。
2.生成hashcode的算法尽量使hashcode的值分散一些,不要很多hashcode都集中在一个范围内,这样有利于提高HashMap的性能。即“分散原则”。
public class MyHashMap extends HashMap {
@Override
public Object get(Object key) {
try {
return super.get(key);
} catch (Exception e) {
return "";
}
}
}