0

I'm a beginner with java and I wanted to know if there was a way to dynamically instantiate an array, that is, being able to add and remove elements by changing the actual size of the array.

chickl
  • 11
  • 3
  • Arrays can be created with a size that can be calculated, but once it's created it has a fixed size. The answer from Klayser shows the class to use as alternative. – Rob Spoor Feb 02 '22 at 20:10
  • Once created, the size of an array cannot be changed. When you need more space, you need to create a bigger array and then copy all the values to the new one. Which is what ArrayList does internally so you don't have to deal with that. – f1sh Feb 02 '22 at 20:15

2 Answers2

2

In java there is a class called Arraylist, to import it import java.util.ArrayList;

you have to declare it with the data type you want it to contain an example below with some strings

ArrayList <String> cars = new ArrayList <String> ();

To add an item just use the .add (item) function like this

cars.add ("Tesla");

to remove instead it is necessary to have the index and with the command .remove (index) you can remove an object

cars.remove(0);
Klayser
  • 334
  • 4
  • 12
-1

Try Arraylist: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

List<String> list = new ArrayList<>();
  • 1
    This snippet will not compile; the class is called `ArrayList` (note the capitalization). Additionally, you should specify the generic type or use [the diamond operator](https://stackoverflow.com/q/4166966) in modern Java code. The snippet then becomes `List list = new ArrayList<>();`. – Julia Feb 02 '22 at 23:05