dorothy
dorothy

Reputation: 1243

How to add another object to an object array

i have java code (array of objects)

 Items[] store = new Items[] { new Items(...) , new Items(...) };

What is the standard method to append to this store array. I am trying not to use ArrayList or other convenient methods for a start. thanks

Upvotes: 0

Views: 125

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

I would do it this way

store = Arrays.copyOf(store, store.length +1);
store[store.length - 1] = newItem;

Upvotes: 0

Hardik
Hardik

Reputation: 17441

try this

Items items1=new Items();
Items items2=new Items();

......
ArrayList<Items> listItems=new ArrayList<Items>();
listItems.add(items1);
listItems.add(items2);

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

The standard way is not to use an array, but rather an ArrayList<Items> which behaves much like an array that can grow or shrink as needed. Then you can simply call myList.add(myItem) to append to it.

If this won't work for you, then please share the details of your requirements.


Edit
You state in an edit:

I am trying not to use ArrayList or other convenient methods for a start.

Please tell us why the stipulation? If you want an array to grow, you'll have to create a new array that is larger than the previous, copy all items to it, and add the new item. It's a lot of work that ArrayList does for you.

Upvotes: 4

Related Questions