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.

Jakub Kubrynski
  • 13,724
  • 6
  • 60
  • 85
Josh
  • 189
  • 3
  • 12

2 Answers2

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
Alex K
  • 8,269
  • 9
  • 39
  • 57
  • 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 Apr 08 '15 at 21:05
  • @Josh sure. See my edit. It is very easy with an ArrayList – Alex K Apr 08 '15 at 21:07
  • 1
    Great thanks! 95% sure that'll work for me so I'll mark as solved. Much appreciated. – Josh Apr 08 '15 at 21:11
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.

theguywhodreams
  • 315
  • 1
  • 8
  • Thanks :) I'll try make Array Lists work for me first. Nice to know about options though. – Josh Apr 08 '15 at 21:06