拡張可能な配列、つまり、配列リストのように容量を増やすことができる配列を作成しようとしています。以下のコードで警告が表示されます。修正する必要がありますか?それを抑制することの結果は何ですか?
import java.util.*;
public class GrowableArray<T>{
private T[] array;
//more variables
GrowableArray{
this.array = (T[]) new Object[10]; // Warning - Type safety: Unchecked cast
//from Object[] to T[]
//more code
}
//more code
完全なコードについては、以下をご覧ください -
import java.util.*;
public class GrowableArray<T>{
private T[] array;
private int increaseSizeBy;
private int currentIndex;//That is first free position available
private int lastIndex;
public GrowableArray(){
this.array = (T[]) new Object[10];
this.currentIndex = 0;
this.lastIndex = 10-1;
this.increaseSizeBy = 10;
}
public GrowableArray(int initialSize){
this.array = (T[]) new Object[initialSize];
currentIndex = 0;
lastIndex = initialSize - 1;
}
public void increaseSizeBy(int size){
this.increaseSizeBy = size;
}
public void add(T anObject){
if(currentIndex > lastIndex){ ;
//create a bigger array
int oldLength = array.length;
int newLength = oldLength + this.increaseSizeBy;
Object [] biggerArray = Arrays.copyOf(array, newLength);
array = (T[]) biggerArray;
currentIndex = oldLength;
lastIndex = array.length-1;
}else{
array[currentIndex] = anObject;
currentIndex++;
}
}
public void display(){
System.out.println();
for(int i = 0; i < this.currentIndex; i++){
System.out.print(array[i] + ", ");
}
System.out.println();
}
public static void main(String[]args){
GrowableArray<Integer> gArr = new GrowableArray<Integer>();
for(int i = 0; i <= 35; i++){
gArr.add(i);
}
gArr.display();
gArr.add(300);
gArr.add(301);
gArr.add(302);
gArr.add(303);
gArr.add(304);
gArr.add(305);
gArr.display();
}
}