我正在尝试创建一个以迭代方式计算数字序列的程序。我很难为我的长体定义动态长度数组。当使用下面的我得到“数组维度丢失”。我在这里错过明显的东西吗?
谢谢
long seq[] = new long[];
完整代码:
public long calculate(long n) {
// If n is one of known values return that value
if(n<=1){
return 0;
}
if(n==2){
return 1;
}
if (n==3){
return 2;
}
// initate array to calculate
long seq[] = new long[];
int x = 0;
seq[0] = 0;
seq[1] = 0;
seq[2] = 1;
seq[3] = 2;
// for loop until reached requested number
for (int i = 4; i<=n; i++){
seq[i] = seq[i-1]+seq[i-3];
}
for (int i =0; i<n; i++){
x++;
}
return seq[x];
}
答案 0 :(得分:0)
您不能编码
long seq[] = new long[];
像这样!必须有一个初始容量。
请参阅ArrayList源:
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
如果要动态插入:
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
答案 1 :(得分:0)
缺少维度是因为,当您编写[n]
时,它是一个维度,而当您编写[n,m]
时,则是二维,并且这样向前发展...
当您刚刚传递空的[]
时。它对填充数组的方式一无所知,因此您需要像这样long[] powers = {..., 2863245995L, 11453115051L, ...};
来填充它
long[] powers = {..., 2863245995L, 11453115051L, ...};
或设置尺寸,这也意味着您需要设置尺寸。因为,您需要使用数字或逗号分隔的数字列表,每个数字代表每个维度的大小。像:long[] heights = new long[4];
如果要强制将其设置为数组,但又要动态更改其大小... C#List
这样做,我个人认为,JAVA ArrayList
应该是相同的:>
Initialize:
create a array of default minimum size which is power of 2,
Set a used element count with name such as Count/Length to the number of element that are initially loaded otherwise 0
Adding element:
if there is more space, add to free slot,
if not, create new array and double the size
then copy all item to the new array.
Add to the Count/Length of array
否则,LinkedList
会完成这项工作,您应该已经知道它是如何工作的...