Java の配列に関する問題を修正する「正しい」方法を探しています。最大値を知らなくても、整数の配列が必要です。
宣言の制限を回避するための現在の解決策:
private ArrayList<Integer> myArray = new ArrayList<>();
このソリューションの問題:
myArray.get(i);
int の代わりに String を返したいのですが、さらに計算するには int が必要です... (私は最後のオプションを推測しています...)
Yes, since you don't know how many items you want your array to hold, you should indeed use an ArrayList. Furthermore myArray.get(i) will indeed return an int, just try
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
int a = myArray.get(0); // autoboxing
System.out.println(a);
The ArrayList is correct. It will not return a String, it will return the Integer. You can get an int from it automatically though because of the autoboxing.
int x = myArray.get(i);
returns an Integer object and the contained int will be passed to your variable.
Firstly this is wrong in java6
private ArrayList<Integer> myArray = new ArrayList<>();
should be
private ArrayList<Integer> myArray = new ArrayList<Integer>();
you'd get an compiler error anyway so i assume its a typo. and your code would most definitely return Integer if you do
myArray.get(i);