2011-03-03 79 views
3

回想我在這裏的基本ADT的東西,並試圖通過學習Java一石二鳥,而我正在努力編寫一個簡單的算法與一個通用鏈表(我創建自己)的合併排序。事實證明,這比我想象的要困難得多!任何人都可以幫我嗎?我開始了對基礎工作,如我在得到進一步會更新這個帖子For循環與泛型數組?

我對通用的鏈表代碼如下:

public class NodeList<T> { 
    private Comparable head; 
    private NodeList tail; 
    public NodeList(Comparable item, NodeList list) { 
    head = item; 
    tail = list; 
    } 

} 

我想在另一個訪問這個類我做了如下的類:

public class MyList<T> { 

    private NodeList<T> nodes; 
    private int size; 
    public MyList() { 
    nodes = null; 
    } 

    public MyList(T[] array){ 
    for(int countArray = 0; countArray <= array.length() ; countArray++) { 
     nodes= new NodeList(value, nodes); 
     size++; 
    } 
    } 

它應該使用鏈接列表從數組中添加通用項目。不幸的是,它並沒有,這是我遇到的第一個問題。我得到的錯誤:

無法找到符號:方法的長度()。

有人可以給我一些建議,我怎麼能解決這個問題?

非常感謝!

+0

爲什麼你想歸併鏈表而不是一個數組支持的名單? Mergesort是用於具有O(1)(恆定時間)元素訪問的列表,但鏈接列表具有O(n)(線性時間)元素訪問。 – 2011-03-03 16:09:17

+0

底部的做法是什麼?你正在循環一個數組,但不使用它的任何值,多次設置和重新設置'nodes',並將'size'設置爲傳入數組的長度。我很困惑。 – 2011-03-03 16:09:45

回答

2

集合類的方法是.size(),或者在數組上它是.length屬性。

但你可以通過任一環具有「增強的」 for循環(又名的foreach):不具有長度()方法,但長度構件在陣列上

for(T element : array) { 
    nodes = new NodeList(value, nodes); 
    size++; 
} 
+0

這也擺脫了潛在的ArrayIndexOutOfBoundsException :) – Thomas 2011-03-03 16:11:31

7

:陣列。長度

此外,你要使用它之前countArray達到array.length之前停止迭代並初始化大小:

final int arrayLength = array.length; 
size = arrayLength; 
nodes = null; 
for(int i = 0; i < arrayLength; ++i) { 
     nodes = new NodeList(array[i], nodes); 
} 

nodes = null; 
size = array.length; 
for(T element : array) { 
     nodes = new NodeList(element, nodes); 
} 
1

lengthfield,不是數組上的方法。刪除括號。

for(int countArray = 0; countArray <= array.length ; countArray++) { 
    nodes= new NodeList(value, nodes); 
    size++; 
} 

這裏寫全構造一個更好的辦法:

public MyList(T[] array){ 
    nodes = null; 
    for(T t : array) { 
     nodes = new NodeList(t, nodes); 
    } 
    size = array.length; 
} 
0

據array.length不array.length()。

for(int countArray = 0; countArray <= array.length ; countArray++) { 

才能解決您的編譯錯誤。

1

除了別人已經發布,你也可能需要使用您的泛型參數T:

public class NodeList<T> { 
    private T head; 
    private NodeList<T> tail; 
    public NodeList(T item, NodeList list) { 
    head = item; 
    tail = list; 
    } 
} 
1

如果你想確保只有可比項目是可能的:

public class NodeList<T extends Comparable<T> > { 
    private T head; 
    private NodeList<T> tail; 
    public NodeList(T item, NodeList<T> list) { 
    head = item; 
    tail = list; 
    } 
} 

public class MyList<T extends Comparable<T>> { 
... 
} 

此外,如果你的構造函數使用var args,你會得到一個更方便創建列表的ient方式:

public MyList(T... array) { 
    for(T item : array) { 
    nodes = new NodeList<T>(item, nodes); 
    } 
    size = array.length; 
} 

這樣,你可以調用構造函數如下:

new MyList<Long>(); //empty list 
new MyList<Long>(1L); //one entry 
new MyList<Long>(1L, 2L, 3L); //3 entries 
Long[] array = new Long[] { 1L, 2L, 3L, 4L }; 
new MyList<Long>(array); //use existing array