我有以下ArrayIntList類,其構造函數定義如下。在最後一個構造函數中,我想要布爾型,如果爲true,則使用該特定元素實例化一個新對象。如果設置爲false,它應該實例化一個具有這麼多容量的新對象。請看我的意思是在這裏的客戶端代碼。它在布爾值爲true時有效。我的類的構造函數不起作用
類文件:
public class ArrayIntList {
private int[] elementData; // list of integers
private int size; // current number of elements in the list
public static final int DEFAULT_CAPACITY = 100;
// post: constructs an empty list of default capacity
public ArrayIntList() {
this(DEFAULT_CAPACITY);
}
// pre : capacity >= 0 (throws IllegalArgumentException if not)
// post: constructs an empty list with the given capacity
public ArrayIntList(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity: " + capacity);
}
elementData = new int[capacity];
size = 0;
}
//takes input list and adds to arrayIntList
public ArrayIntList(int[] elements) {
this(Math.max(DEFAULT_CAPACITY,elements.length*2));
for (int n: elements){
this.add(n);
}
}
//creates an arrayIntlist with data of element
public ArrayIntList(int element,boolean notCapacity) {
this();
if (notCapacity) {
add(element);
}
//returns the totalCapacity NOT SIZE
public int getCapacity() {
return elementData.length;
}
}
客戶端代碼:
public class ArrayIntListExample {
public static void main(String[] args) {
// Create a new list and add some things to it.
ArrayIntList list = new ArrayIntList();
//*** here is my question about ****//
ArrayIntList list1 = new ArrayIntList(2, false);//should give [] with capacity of two
ArrayIntList list2 = new ArrayIntList(2, true);//should give [2]
//*** ****************************** ****//
int[] array={2,3,4,5};
ArrayIntList list3 = new ArrayIntList(array);
list.add(12);
list.add(3);
list.add(3);
System.out.println("list = " + list);
System.out.println("list1 = " + list1);
System.out.println("list2 = " + list2);
System.out.println("list2 = " + list3);
System.out.println("capacity of list1" + list1.getCapacity());//prints 100 but it must be 2
}
}
您沒有任何代碼,將做到這一點。 – SLaks
是什麼問題?構造函數的代碼看起來不錯(除了一個事實,即你缺少一個'}',我以爲是一個錯字)... – jahroy
什麼是與你的構造函數,你不希望發生的事情? – Kon