2

Is it possible to reset the number of values in an array after it's already been set? I have defined the number of values in the array through a variable, later that variable is updated by the user and I need to size of the array to be updated with it.

Ie:

numberOfPeople = 2;
Person person[] = new Person[numberOfPeople];

Later:

if(valueSelected == 3) {
numberOfPeople = 3; }

Above is just a very simplified example but basically that's what I've got, I just need the array size to actually change when the if statement being executed.

0

2 Answers 2

5

No, you can't change the length of the array once it's been created.

For that, I'd recommend using an ArrayList:

ArrayList<Object> arrayList = new ArrayList<Object>();
Object o = new Object();
arrayList.add(obj);

It can keep growing to any length you'd like.

You can read more about ArrayLists from the official oracle document here.

For removing entries, just use the .remove() method:

Either

arrayList.remove(Object o); //removes occurrence of that object 

OR

int index = 0;
arrayList.remove(index);  //removes the object at index 0
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Alex. I'll do some further research into ArrayLists. I them to be able to handle removing entries from the list too (the user might just have 1 person instead of the default 2), but from my quick search it seems that's possible so hopefully it should work out.
@Josh sure. See my edit. It is very easy with an ArrayList
Great thanks! 95% sure that'll work for me so I'll mark as solved. Much appreciated.
2

If you still want to stick with using arrays, though, you'd have to make a new array with a bigger size and copy all the data from the old one into the new one.

I'd still suggest Alex K's answer. It's a lot easier.

1 Comment

Thanks :) I'll try make Array Lists work for me first. Nice to know about options though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.