2014-10-09 156 views
-1
import java.util.*; 
import javax.annotation.*; 



public class Test6 
{ 

    private static final @NonNull Map<Test6,Integer> cache= new HashMap<Test6, Integer>(); 
    private final @NonNull String id; 

    public Test6(@NonNull String id) 
    { 
     this.id = id; 
    } 
    public static void main(String args[]) 
    { 
     Test6 foo = new Test6("a"); 
     cache.put(foo,1); 
     // System.out.println("inside foo******"+cache.get(foo)); 
     // System.out.println("inside******"+cache.get(new Test6("a"))); 
     System.out.println(cache.get((new Test6("a"))).intValue()); 
    } 

} 

我应该实现一些防止此程序崩溃的方法吗?Java程序崩溃

+1

您可以发布一些关于您在程序崩溃时获得的错误类型的其他信息吗? – therealrootuser 2014-10-09 06:11:12

+1

你能更具体吗?你在尝试什么? – 2014-10-09 06:12:01

+0

你是什么意思?它的程序不是物理服务器。您可能会在.intValue()调用中获得NullPointerException。我们称之为异常而不是崩溃。 – Nazgul 2014-10-09 06:19:27

回答

1

它不崩溃,你得到NullPointerException

System.out.println(cache.get((new Try("a"))).intValue()); 

这里cache.get((new Try("a")))=null然后null.intValue()原因NPEcache.get((new Try("a")))=null因为你没有覆盖equals()hashCode()

只是可以通过改变你的main()方法脱身。

public static void main(String args[]) { 
Try foo = new Try("a"); 
cache.put(foo, 1); 
System.out.println(cache.get(foo).intValue()); 
} 

还有重要的一点。由于Key是您的自定义类,因此您可以用这种方式处理代码以覆盖equals()hashCode()

如:

class Test { 
private static final 
@NonNull 
Map<Test, Integer> cache = new HashMap<>(); 
private final 
@NonNull 
String id; 

public Test(@NonNull String id) { 
    this.id = id; 
} 

public static void main(String args[]) { 
    Test foo = new Test("a"); 
    cache.put(foo, 1); 
    System.out.println(cache.get(new Test("a")).intValue()); 
} 

@Override 
public boolean equals(Object o) { 
    if (this == o) return true; 
    if (!(o instanceof Test)) return false; 
    Test aTry = (Test) o; 
    if (!id.equals(aTry.id)) return false; 
    return true; 
} 

@Override 
public int hashCode() { 
    return id.hashCode(); 
} 
} 
0

为了在你需要一个HashMap一键覆盖hashCode(),像

@Override 
public int hashCode() { 
    return id.hashCode(); 
} 

而且你应该重写equals()

@Override 
public boolean equals(Object obj) { 
    if (obj instanceof Test6) { 
    Test6 that = (Test6) obj; 
    return this.id.equals(that.id); 
    } 
    return false; 
} 

至少你的代码输出为

1 

当我做了上述改变。