java数组nullpointer [英] java array nullpointer
问题描述
我正在尝试查找数组的最小值.该数组包含Nodes-一个包含元素E和优先级int的节点.我想在阵列中找到优先级最低的节点.
I'm trying to find minimum of an array. The array contain Nodes - a node contains of an element E and a priority int. Im want to find the Node in the array with the smallest priority.
@Override
public E min() {
Node temp = S[0];
for(int i = 1; i<S.length; i++){
int prio= S[i].getPrioritet(); <-- nullpointer excp.
if(prio<temp.getPrioritet()){
temp = S[i];
}
}
return temp.getElement();
但是当我尝试使用它时,我得到了一个nullpointer异常.有人知道我在做什么错吗?
But i get an nullpointer exception when i try to use it. Does anybody know what im doing wrong?
这是我的考试:
PrioritetArraySorteret<String> p = new PrioritetArraySorteret<String>();
p.insert(1, "Hello");
p.insert(3, "Hi");
p.insert(4, "Hawdy");
System.out.println(p.min());
}
推荐答案
这仅表示数组 S
的索引之一处的元素为空.也许您以 n
的大小初始化了数组,但填充的位置少于 n
个位置.
It simply means that the element at one of the indexes of array S
is null. Maybe you're initialized the array at a size n
but filled in less than n
positions.
这样修改可能会解决此问题:
Altering like this will probably fix it:
for(int i = 1; i<S.length; i++){
if(S[i] != null) {
int prio= S[i].getPrioritet(); <-- nullpointer excp.
if(prio<temp.getPrioritet()){
temp = S[i];
}
}
}
也就是说,您可能在这里重新发明了轮子.使用一个简单的 ArrayList
参数化为您定义的某种类型,该类型封装了一个值和优先级.然后,您可以使用具有优先级的 compareTo
方法让该类型实现 Comparable
,或者编写一个 Comparator
来查找最小值:
That said, you might be reinventing the wheel here a bit. Using a simple ArrayList
parameterized with some type that you define which encapsulates a value and priority would do. You could then have that type implement Comparable
with a compareTo
method that uses the priority, or write a Comparator
to use for finding the minimum:
List<YourType<String>> list = new ArrayList<YourType<String>>();
Collections.min(list);
或者,如果您使用的是自定义比较器:
Or, if you're using a custom Comparator:
Collections.min(list, yourComparator);
-编辑了 min
,而不是 sort
.抱歉.
-- edited for min
instead of sort
. Sorry.
这篇关于java数组nullpointer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!