2014-10-09 109 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 

當我做了上述改變。