java - NullPointerException in put method of HashMap -
i know been asked many times before still cant understand mistake..
this normal code writing counting number of repetitions in array( :) might long method doing this, kindly suggest smaller way if can think of)
public int find(int[] sequence) { arrays.sort(sequence); int temp=0,count=0,j=0; hashmap<integer,integer> data = new hashmap<integer,integer>(); for(int i:sequence){ integer c = new integer(count); integer d = new integer(j); if(i!=temp) { if(count!=0) data.put(c,d); count++; j=1; temp=i; } else j++; } count++;//this 1 causes error //system.out.println(count); integer c = new integer(count); integer d = new integer(j); data.put(c,d); long ans = theswapsdivtwo.factorial(sequence.length); for(int i=1;i<=data.size();i++){ ans /= theswapsdivtwo.factorial(data.get(i).intvalue()); system.out.println(data.get(i)); } return (int)ans; } public static long factorial(int n) { long fact = 1; // result (long = 1; <= n; i++) { fact *= i; } return fact; }
the put
method doesn't produce errors in for
loop implementation outside loop.
error this:
java.lang.nullpointerexception @ theswapsdivtwo.find(theswapsdivtwo.java:54) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:39) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:25) @ java.lang.reflect.method.invoke(method.java:585) @ com.topcoder.services.tester.java.testprocess$runner.run(testprocess.java:386)
p.s. count++ caused error... foolish really.. loop going out of bounds..
this line should giving npe:
theswapsdivtwo.factorial(data.get(i).intvalue());
i.e. data.get(i)
not present (1<=i<=data
), either have null
check on each get
value or make sure in logic i
present map require refer.
a test putting null:
map<integer, integer> m = new hashmap<integer, integer>(); m.put(null, null); system.out.println(m);
it prints:
{null=null}
Comments
Post a Comment