0

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

1
  • You cannot resize an array: once it's made you'll have to overwrite it with a new one. That's why you're advised to use an ArrayList which allows easy resizing in your collection. Commented Nov 30, 2013 at 4:37

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ok. thanks. that's troublesome. Ok i will try to use ArrayList
1

try this

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

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

Comments

0

I would do it this way

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.