Search code examples
javaarrayscollectionssizehardcode

Java array declaration without hard coding the size


How can I initialize an array of objects of a class in another class without hardcoding its size?


Solution

  • Use a List. The size does not need to be declared on creation of the List. The toArray() method will return an array representation of the list. There are multiple implementations you can use but the most popular tends to be ArrayList (though it is best to map the implementation to your particular situation).