There is a constant variable as array:

 List<String> as = new ArrayList(Arrays.asList("a", "b", "c", "d")); 

In the process, the elements of the array are added and removed. How to save a modified array when exiting the program?

At the moment when I start the program, the array is initialized in its original form. Which team will save the new elements (ā€œaā€, ā€œeā€, ā€œzā€) to the variable as ?

  • There are many options: 1. to the base 2. to the file (look towards serialization) - JVic
  • this is understandable, I wanted to save the new elements in the variable as - Hellraiser
  • What does "save new variables" mean? Here is an example of saving the entire array to a file and filling it from a file: int [] az = {10, 20, 30}; ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("filename")); oos.writeObject (az); oos.flush (); oos.close (); ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("filename")); int [] az = (int []) ois.readObject (); - JVic

2 answers 2

Before completing, do this:

 ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("filename")) ; oos.writeObject(as); oos.flush(); oos.close(); 

When opening do this:

 ObjectInputStream ois = new ObjectInputStream( new FileInputStream("filename")); as = (ArrayList<String>) ois.readObject(); ois.close() 
  • thank you so much - Hellraiser

When the program ends after the end or forcibly, then all memory is freed. Therefore, as Arhad said, to restore the state of an ArrayList you need to either get an object from the database or from a file, as I understand it, this is serialization and deserialization of the object.

Well, to get it you need to save first.

to as can be saved with as.add("ololo");

  • I just haven't worked with bases yet - Hellraiser
  • if I understood correctly, the question was the following "how to add an element to the list" ??? I have only one comment B @ # $, lived out ... - JVic
  • He did not mean to save somewhere, just blunted a bit with an explanation. - JAVAvladuxa