如何实现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 中有没有像delphi 或vc++中的groupbox控件啊? 找程序理解理论 Workbook读取EXCEL设置时间格式 如何将JTree数据传给一个WEB页面上的JApplet? 新手的一系列问题.请大侠HELP! 一个简单的问题 初学java,请教一个时间对比算法。 怎样实现图片在applet中来回左右移动? 关于applet与数据库的通讯 求: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 "";
}
}
}