2011-03-03 83 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