Java程序崩溃

时间:2014-10-09 06:08:59

标签: java

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());
    }

}

我应该实施任何方法来防止此程序崩溃吗?

2 个答案:

答案 0 :(得分: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());
}

有一点很重要。您可以通过这种方式处理代码,以覆盖equals()hashCode(),因为Key是您的自定义类。

例如:

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();
 }
}

答案 1 :(得分: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

当我做出上述修改时。

相关问题