Ich habe versucht, meine eigene implementierte LinkedList zu verwenden.Fehler bei der Verwendung eigene implementierte verknüpfte Liste
public class LinkedList<O> {
private Node<O> first,last;
private int count;
public LinkedList(){}
public Node getfirst(){
if(first==null) return null;
else return first;
}
public Node getLast(){
if(first==null) return null;
else return last;
}
public int getSize(){
return count;
}
public void addFirst(Object x){
if(first==null)first=last=new Node(x);
else{
Node temp =new Node(x);
temp.next=first;
first=temp;
}
count++;
}
public void addLast(Object x){
if(first==null)first=last=new Node(x);
else{
last.next= new Node(x);
last=last.next;
}
count++;
}
public void add(Object x,int index){
if(index==0)addFirst(x);
else if(index>=getSize())addLast(x);
else{
Node current=first;
for(int i=0; i<index-1;i++)
current=current.next;
Node temp = new Node(x);
temp.next=current.next;
current.next=temp;
count++;
}
}
public boolean removeFirst(){
if(first==null)return false;
else if(first==last){
first=last=null;
count--;
return true;
}
else{
first=first.next;
count--;
return true;
}
}
public boolean removeLast(){
if(first==null)return false;
else if(first==last){
first=last=null;
count--;
return true;
}
else{
Node current=first;
for(int i=0;i<getSize()-2;i++)
current=current.next;
last=current;
last.next=null;
count--;
return true;
}
}
public boolean remove(int index){
if(index==0)return removeFirst();
else if(index==getSize()-1)return removeLast();
else{
Node current=first;
for(int i=0;i<index-1;i++)
current=current.next;
current.next=(current.next).next;
count--;
return true;
}
}
}
public class Node<E> {
E element;
Node<E> next;
public Node(E element) {
this.element = element;
}
}
wenn ich verwendet:
for(Book b:books){
System.out.println(b);
}
es gab mir eine Fehlermeldung: Kann nur ein Array oder eine Instanz von java.lang.Iterable
So durchlaufen habe ich versucht, zu verwenden:
for(Book current=books.getFirst(); current !=null; current=current.next){
System.out.println(current);
}
Es Druck:
[email protected]
[email protected]
[email protected]
und wenn ich collection.sort verwendet
Collections.sort(books,new Comparator<Book>()){
public int compare(Book book1, Book book2) {
return book1.getTitle().compareToIgnoreCase(book2.getTitle());
}
}
Es gab mir: Die Methode sort (List, Vergleicher) in der Art Collections ist nicht anwendbar für die Argumente (LinkedList, Stock.MyTitleComp)
Kann jemand bitte diese Fehler erklären und beheben?
alles funktioniert, aber jetzt gibt es mir java.lang.NullPointerException bei Collections.sort (Bücher, neue Comparator()) –
Nicky
vor der Verwendung von Collections.Sort funktioniert es gut, gibt es keine Nullwerte – Nicky