对于具有通用数组的循环? [英] For loop with a generic array?
问题描述
在这里回顾我的基本ADT知识,然后尝试通过学习Java来用一块石头杀死两只鸟。我正在尝试编写一种用于通用排序列表的归并排序的简单算法(这是我自己创建的)。事实证明,这比我最初想象的要困难得多!有人可以帮我吗?我将开始研究基础知识,并在以后继续学习。
Going back over my basic ADT stuff here, and trying to kill two birds with one stone by learning Java while I amTrying to write a simple algorithm for a merge sort with a generic linked list ( which I am creating myself). It's proving to be far more difficult than I had first imagined ! Can anyone help me out please ? I will start out working on the basics and will update this post as I get further in.
我的通用链接列表代码如下:
My code for the generic linked list is as follows :
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++;
}
}
应使用数组从数组中添加通用项链表。不幸的是,这不是我遇到的第一个问题。我收到错误消息:
which should add generic items from an array, using a linked list. Unfortunately, it doesn't and this is the first problem I have encountered. I am getting the error :
找不到符号:方法length()。
cannot find symbol : method length().
有人可以给我一些如何解决此问题的建议吗?
Can someone give me some advice on how I could fix this?
非常感谢!
推荐答案
在数组上没有length()方法,但是有一个length成员:array.length
on the array you don't have a length() method but a length member : array.length
另外,您将要在countArray到达array.length和初始化大小之前停止迭代,然后再使用它:
Additionally, you'll want to stop iterating before countArray reaches array.length and initialise size before using it:
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);
}
这篇关于对于具有通用数组的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!