2

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.

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

4 Answers 4

2

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?

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

1 Comment

It's quite simple, actually: just copy-paste the exact implementation of ArrayList. You surely can't beat that.
1

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.

1 Comment

Especially when you're struggling to add an element to an array.
1

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

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.