I am trying to convert a section of code from using an ArrayList of custom objects to a regular array.

Previous my definition was

ArrayList<Room> rooms = new ArrayList<Room>();

Which I have now changed to

Room[] rooms;

Previously I used the below line to add items to the array list

rooms.add(new Room(1,1,30,false,true,true,false));

But I am now struggling to find the way I should simply add individual items to the array throughout code.

share|improve this question

Are you asking how to add elements of an array into an ArrayList (or vice versa)? – fireshadow52 Nov 22 at 21:33
I want to move away from using the array list, I want to add elements from an arraylist to an array. – mr.user1065741 Nov 22 at 21:35
List<Room> rooms = new ArrayList<Room>(); is much more preferable (coding to interface principle) – Jiri Kremser Nov 22 at 22:10
feedback

4 Answers

up vote 2 down vote accepted

I think you are best sticking with an arrayList here, but just to give you a bit more light on it.

To do what you are trying to do, you will have to keep a index integer which will just point to the current position in the array, then when you add you can increment this and add the new object into the next poisition. When you get to the maximum size of your array, you will need to expand it. You will find that there has been questions on expanding an array which have been asked already and you can find the answers here: Expanding an Array?

share|improve this answer
It's quite simple, actually: just copy-paste the exact implementation of ArrayList. You surely can't beat that. – Marko Topolnik Nov 22 at 21:55
feedback

If you can live with a fixed-size array, that gives you at least a slight chance of success. If not, you can't beat ArrayList and if your mission is to succeed without reimplementing it, then it is an impossible mission.

You should really give more insight into the exact rationale for rewriting your code like that, it would give us some chance to properly help you.

share|improve this answer
Especially when you're struggling to add an element to an array. – Frank Pavageau Nov 22 at 21:54
feedback

I can recommend:
Use Arraylist as Long you Need to insert Elements. Once th Array is final Convert to Array.

share|improve this answer
feedback

If you need to increase the size of the array when adding another element, you have to construct another array with the size of the old array +1. Afterwards, you would copy the contents of the old array over to the new array (the bigger array).

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.