How to add an element to ArrayList

0

Hello Good afternoon, I went because I have a question if you could help me.

I want to create a ArrayList of a class, have a dynamic array of objects of a class, I'm doing it in the following way:

  ArrayList<Persona> pruebas = new ArrayList();
  pruebas.set(0, new Persona());                                 
  System.out.println(pruebas.get(0).getNombre());

but it throws me an execution error:

  

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index:   0, Size: 0

Can you help me please.

    
asked by Javier 23.02.2018 в 18:42
source

4 answers

0

You mark that error because you do not have any item on your list

First you must add elements as follows:

personas.add(new Presona());

And if you are going to replace that element now if you do already have elements in your list:

personas.set(0, new Presona());

Example

    
answered by 23.02.2018 / 18:56
source
2

First and foremost, the arraylist class is explained in manuals throughout the web.

For example, here

Having said that, the set method has the signature:

  

E set (int index, E element)

     

This method replaces the element at the specified position in this   list with the specified element.

Which means that it is used to replace an existing element in the list. Thing here is not what you want to do, but you want to add.

To add elements, the method is used

  

boolean add (E e)

     

This method appends the specified element to the end of this list.

This method adds an element to the end of the list. Since this list has no elements, this is exactly what you wanted to do. therefore, your code should be:

pruebas.add(new persona());
    
answered by 23.02.2018 в 18:52
1

As you can see, your arrangement does not have an index 0 defined, as in the Exception that says index: 0 size 0 which means that you have not defined any of that

on the contrary you could use,

personas.add(new Presona());
    
answered by 23.02.2018 в 18:50
1

The error:

  

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

is because you try to get the information of an object in the index 0 of your ArrayList which does not really exist.

The method you must use to enter an element to your ArrayList is add () .

  

add () : Inserts the item specified in the position   specified in this list. Change the item currently in that   position (if it exists) and any subsequent element on the right   (adds one to your indexes).

Since the method

  

set () replaces the element at the position specified in this list with the specified element.

set () , replace but not insert, therefore insert elements using the set () :

 ArrayList<Persona> pruebas = new ArrayList();
      //pruebas.set(0, new Persona());
      pruebas.add(0, new Persona());
    
answered by 23.02.2018 в 19:07