我知道它之前被问过很多次,但我仍然无法理解我的错误..
这只是我编写的一个普通代码,用于计算数组中的重复次数(:)这可能是一个很长的方法,如果您能想到,也请建议一个更小的方法)
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 one causes the 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; // this will be the result
for (long i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
put
方法不会在 for
中产生任何错误循环,但它适用于循环外的实现。
错误是这样的:
java.lang.NullPointerException
at TheSwapsDivTwo.find(TheSwapsDivTwo.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at com.topcoder.services.tester.java.TestProcess$Runner.run(TestProcess.java:386)
附注count++ 导致了错误...真的很愚蠢..循环超出范围..
最佳答案
这是应该给出 NPE 的行:
TheSwapsDivTwo.factorial(data.get(i).intValue());
即data.get(i)
不存在 ( 1<=i<=data
),或者有 null
检查每个get
值或确保您的逻辑全部 i
存在于您需要引用的 map 中。
放置 null 的测试:
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
m.put(null, null);
System.out.println(m);
它打印:
{null=null}
关于java - HashMap的put方法出现NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16668840/