Reputation: 13
I am making an ArrayList of objects that will be displayed in a ListView. When I use Object[] ObjectList = new Object[length]
it expects an exact length for the entire array upon creation. I have tried making the value of the length an int variable but it appears it doesn't update the length when the variable is changed. How can I accomplish this? I am kinda new to Java, so thanks to anyone who helps out!
Upvotes: 0
Views: 430
Reputation: 131396
I will not repeat what others have very well said.
About your actual problem, android.widget.ListView
is designed to be populated with array type.
Now if data used to populate the ListView
have a size variable and may often changed, you have an alternative : using an ArrayList
wrapped in an ArrayAdapter
.
During the onCreate()
method you could create the adapter and set it to the ListView
:
List<String> list = new ArrayList<>();
...
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.listview,
arrayList);
listView.setAdapter(arrayAdapter);
Now, you don't have any longer the problem of the fixed size array as you use an ArrayList
that doesn't have this limitation.
Upvotes: 2
Reputation: 140465
Arrays have a fixed size. Once an array is created, the size can't be changed any more. You can only create a new array and change the reference your variable is holding!
In other words - assume you start with:
Object[] items = new Object[5];
Later you figure: I need more space:
Object[] moreItems = new Object[15];
And then you can use System.arraycopy() to copy the content of the first array into the second.
For the record:
ArrayList
uses the approch described above under the covers to implement that "dynamically" growing array experience for youUpvotes: 2
Reputation: 1906
Use List
interface of Collections framework. E.g. List<String> data = new ArrayList<>()
. You can conver it to array if you need with data.toArray()
method
Upvotes: 3