Reputation: 61
In Java, I am trying to read files and then I want to put them in an array. But when I declare an array, an error occurs because of unknown length. Here's an example:
Object unsortedInt[];
try {
BufferedReader bR = new BufferedReader(new FileReader(x));
String values = bR.readLine();
int index=0;
while (values != null){
unsortedInt[index]=values;
values= bR.readLine();
index++;
}
bR.close();
}
catch (IOException e) {
e.printStackTrace();
}
I can work with arraylist for this problem but is there a way that works with arrays ?
Upvotes: 1
Views: 755
Reputation: 2598
You can try something like below :
public class AddItemToArray {
private int[] list = new int[0];//you should initialize your array first.
public int[] getList() {
return list;
}
public void push(int i) {
int fLen = list.length;//you can check the current length of your array and add your value to the next element of your array with the copy of previous array
list = Arrays.copyOf(list, list.length + 1);
list[fLen] = i;
}
public static void main(String[] args) {
AddItemToArray myArray = new AddItemToArray();
myArray.push(10);
myArray.push(20);
myArray.push(30);
System.out.println(Arrays.toString(myArray.getList()));
}
}
Upvotes: 0
Reputation: 1500245
I can work with arraylist for this problem but is there a way that works with arrays ?
Only by reproducing the logic of ArrayList
, basically. No, there's no way of getting a variable-length array. Arrays in Java just don't support that.
If you need an array later, you could create an ArrayList
and then call toArray
to create the array afterwards.
You could read the file once just to count the lines and then again to actually read the data... but it would be much better just to use an ArrayList
while you read.
Upvotes: 2
Reputation: 393781
In order to work with arrays, you must initialize the array to some initial length. You can later create a larger array (and copy the contents of the original array to it) if the current array is too small for your input. That's the way ArrayList
is implemented.
Upvotes: 2