3

在这里回顾我的基本 ADT 内容,并尝试通过学习 Java 用一块石头杀死两只鸟,同时我正在尝试编写一个简单的算法,用于使用通用链表(我自己创建)进行合并排序。事实证明这比我最初想象的要困难得多!谁能帮帮我?我将开始研究基础知识,并在我进一步深入时更新这篇文章。

我的通用链表代码如下:

    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++;
    }
  }

它应该使用链表从数组中添加通用项。不幸的是,它没有,这是我遇到的第一个问题。我收到错误消息:

找不到符号:方法长度()。

有人可以就如何解决这个问题给我一些建议吗?

非常感谢!

4

6 回答 6

7

在数组上,您没有 length() 方法,但有一个长度成员:array.length

此外,您需要在 countArray 达到 array.length 之前停止迭代并在使用它之前初始化 size :

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);
}
于 2011-03-03T16:04:37.617 回答
2

集合类上的方法是.size(),或者数组上的方法是.length属性。

但是您可以使用“增强的” for 循环(又名 foreach)来循环其中的任何一个:

for( T element : array ) {
    nodes = new NodeList( value, nodes );
    size++;
}
于 2011-03-03T16:04:37.320 回答
1

length是数组上的字段,而不是方法。删除括号。

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;
}
于 2011-03-03T16:04:49.190 回答
1

除了其他人发布的内容之外,您可能还想使用通用参数 T:

public class NodeList<T> {
  private T head;
  private NodeList<T> tail;
  public NodeList( T item, NodeList list ) {
    head = item;
    tail = list;
  }
}
于 2011-03-03T16:07:47.107 回答
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,您将获得一种更方便的创建列表的方法:

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
于 2011-03-03T16:14:09.883 回答
0

它是 array.length 而不是 array.length()。

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

将解决您的编译错误。

于 2011-03-03T16:06:36.260 回答