Java program crashing -



Java program crashing -

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

should implement methods prevent programme crashing?

it not crash, getting nullpointerexception

system.out.println(cache.get((new try("a"))).intvalue());

here cache.get((new try("a")))=null null.intvalue() cause npe. cache.get((new try("a")))=null since didn't override equals() , hashcode()

just can out set changing main() method.

public static void main(string args[]) { seek foo = new try("a"); cache.put(foo, 1); system.out.println(cache.get(foo).intvalue()); }

but there of import point. can work code in way override equals() , hashcode() since key custom class.

eg:

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) homecoming true; if (!(o instanceof test)) homecoming false; test atry = (test) o; if (!id.equals(atry.id)) homecoming false; homecoming true; } @override public int hashcode() { homecoming id.hashcode(); } }

java

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -