stack mek
stack mek

Reputation: 11

Moving all values one up and putting new value to the bottom

I have an array[8] and freeIndex = 0. How can I add all the values in the array up one position and add a new value to the last position? Would the simplest answers be

amuletHolder[8] = amuletHolder[7];
amuletHolder[7] = amuletHolder[6];
amuletHolder[6] = amuletHolder[5];
amuletHolder[5] = amuletHolder[4];
amuletHolder[4] = amuletHolder[3];
amuletHolder[3] = amuletHolder[2];
amuletHolder[2] = amuletHolder[1];

How to add the new value to the bottom?

Upvotes: 1

Views: 52

Answers (2)

182764125216
182764125216

Reputation: 956

Is there a reason you need an array?

A LinkedList has a lot of these capabilities built in and can be done quite dynamically something like this:

updateList(list, delId, addtId, newItem){
    list.remove(delId);
    list.add(addId, newItem);
}

or a Queue would be better if you strictly go FIFO

updateQueue(queue, newItem){
  queue.remove();
  queue.add(newItem);
}

EDIT: But if you really need an array and need to keep [0] empty I don't see a problem with what you have. It does use a couple more lines than the loop suggested by others but if you only have 8 elements it isn't significant.

to add the new item and leave [0] empty just add array[1]=newItem;

array[7]=array[6];
array[6]=array[5];
array[5]=array[4];
array[4]=array[3];
array[3]=array[2];
array[2]=array[1];
array[1]=newItem;

Or use a loop as others have suggested; something like:

for(int i=7;i>1;i--){
  array[i]=array[i-1];
}
array[1]=newItem;

Upvotes: 1

DarkMatter
DarkMatter

Reputation: 1017

With a for loop:

for (int i = length - 1; i > 0; --i) {
    amuletHolder[i] = amuletHolder[i - 1];
}
amuletHolder[0] = newValue;

Side note: If you array is length 8 valid index are 0-7. Your code will throw ArrayIndexOutOfBoundsException on the first line.

Upvotes: 2

Related Questions