Create an instance of another ArrayList

3

I have an ArrayList in a class and I want to reference it in another class, I've read that I can copy an ArrayList like this:

ArrayList<Persona> profesor= new ArrayList<>(persona);

However, every time I run it gives me a NullPointerException as if the ArrayList were referring to a valid object.

I am using it in this serializer method.

        public void serializar() {

      ArrayList<Contacto> contacto= new ArrayList<>(arreglo);

    try {
        FileOutputStream fos= new FileOutputStream("contactos.dat");
        ObjectOutputStream oos= new ObjectOutputStream(fos);

        if(oos != null)
        {
            oos.writeObject(contacto);
            oos.close();
            JOptionPane.showMessageDialog(null, "Contacto guardado");
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Hubo un error en el proceso\n"
                + "Ha ocurrido el siguiente error: \n"+e);
     }
  }
}
    
asked by David Calderon 12.06.2016 в 16:15
source

1 answer

1

Why do not you just use a getter?

Class Contactos {

    private List<Contacto> contactos;

    ...

    public List<Contacto> getContactos() { return contactos; }
}

If only that list will exist throughout the application, you can do a Singleton that contains the list and use it when necessary . Or you can also make it static.

Regarding the NullPointerException is because the list you are passing is null; has no reference.

    
answered by 12.06.2016 / 21:14
source