我是Java和OOP的新手,前面學過的語言是C. 我想創建一個鏈接列表來擴展AbstractList和允許使用Collections.sort()函數。問題是當我調用Collections.sort()函數時,我得到一個nullPointerException。我的猜測是,這個異常來自於我列表中最後一個節點是空的(所以我可以知道列表結束的位置)。Java LinkedList實現(來自AbstractList)在Collections.sort上給出nullPointerException
class Node
{
Object o;
Node next;
public Node(Object n)
{
o = n;
next = null;
}
}
class LinkList extends AbstractList
{
Comparator c;
public Node head, last;
public LinkList(Comparator c)
{
this.c = c;
head = null;
last = null;
}
@Override
public boolean add(Object a)
{
Node t = new Node(a);
if(last == null)
{
head = t;
last = t;
last.next = null;
}
else //thanks, hyde
if(last != null)
{
last.next = t;
last = t;
last.next = null;
}
return true;
}
@Override
public Object get(int a)
{
Node it = head;
int contor = 0;
while(it!=null && contor<a)
{
it = it.next;
}
if(it!=null)
{
return it;
}
else
return null;
}
@Override
public Object set(int i, Object a)
{
Node it = head;
int contor = 0;
Node aux;
while(it!=null && contor<i)
{
it = it.next;
}
if(it!=null)
{
aux = it;
it.o = a;
// Collections.sort(this,c);
return aux;
}
else
return null;
}
@Override
public int size()
{
Node it = head;
int contor = 0;
while(it!=null)
{
contor++;
it = it.next;
}
return contor;
}
@Override
public int indexOf(Object a)
{
Node it = head;
int contor = 0;
while(it!=null && it.o.equals(a)==false)
{
it = it.next;
contor++;
}
if(it!=null)
{
return contor;
}
else
return -1;
}
}
public class Test
{
public static void main(String args[])
{
LinkList lista = new LinkList(new Comparator(){
@Override
public int compare(Object o1, Object o2)
{
int s1 = (int) o1;
int s2 = (int) o2;
return s2-s1;
}
});
lista.add(2);
lista.add(3);
Collections.sort(lista); //this is line 156
System.out.println(lista.size());
}
}
基本上,我添加了兩個元素,我嘗試對列表進行排序,並得到nullPointerException。這感覺非常令人沮喪,因爲我無法控制排序功能。
Exception in thread "main" java.lang.NullPointerException
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
at Ex6.main(Ex6.java:156)
Java Result: 1
我還沒有看過'java.util.ComparableTimSort'的源代碼,但不知何故,我認爲它不能通過調用'add'來工作。請展示更多你的方法。 –
您的add方法將第一個節點添加兩次....使用* else *。 – hyde
@RobinGreen:添加了其餘的方法。 –