我有以下 ArrayIntList 类,其构造函数定义如下。在最后一个构造函数中,我想要布尔值,如果为真,则实例化一个包含该特定元素的新对象。如果设置为 false,它应该只实例化一个具有那么多容量的新对象。请查看客户端代码以了解我的意思。它在布尔值为真时起作用。
类文件:
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
}
}