publicclassGrowableArray{privatefinalintdefault_capacity=4;privateintcount;privateT[]array;publicGrowableArray(){count=0;array=(T[])(newObject[default_capacity]);//这里...
public class GrowableArray{
private final int default_capacity = 4;
private int count;
private T[] array;
public GrowableArray(){
count = 0;
array = (T[])(new Object[default_capacity]); //这里
}
public int Size(){
return count;
}
public void add(T elt){
if(count == array.length){
expandCapacity();
}
array[count] = elt;
count++;
}
private void expandCapacity(){
T[] larger = (T[])(new Object[array.length*2]); //还有这里应该怎么改
for(int index=0;index
larger[index] = array[index];
}
array = larger;
}
public T get(int index) throws ArrayIndexOutOfBoundsException{
if (index>count||index<0){
throw new ArrayIndexOutOfBoundsException("Error index");
}
T result = array[index];
return result;
}
public void set(int index, T elt) throws ArrayIndexOutOfBoundsException{
if (index>count||index<0){
throw new ArrayIndexOutOfBoundsException("Error index");
}
array[index]= elt;
}
public String toString(){
String result = "";
for(int index=0;index>=0;index++){
result += array[index]+"\n";
}
return result;
}
public static void main(String[] args){
GrowableArray test = new GrowableArray();
try{
for(int i=0;i<10;i++){
int rand = (int)(Math.random()*10+1);
System.out.print(rand);
test.add(rand);
System.out.println(test.toString());
}
System.out.println(test.Size());
test.set(4,7);
System.out.println(test.get(4));
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
C:\class\Ass11>javac GrowableArray.java -Xlint
GrowableArray.java:8: 警告:[unchecked] 未经检查的类型使用
找到: java.lang.Object[]
需要: T[]
array = (T[])(new Object[default_capacity]);
^
GrowableArray.java:21: 警告:[unchecked] 未经检查的类型使用
找到: java.lang.Object[]
需要: T[]
T[] larger = (T[])(new Object[array.length*2]);
要求使用泛型 新建个默认长度为4的数组
add 是添加value到组尾 并且当组 长度到最大时新建长度X2的数组并且拷贝原有原素
目的是要将10个10 以内的随机数添加到数组中
并且在每个添加之后输出数组
之后输出数组长度
使用set将index 4 value改成7
输出 index 4 但是最后只输出了一个数
展开