I have Snapshot class. Inside class I have restore method which needs to restore previous values of list. How I can prevent list element to change values..
Blockquotepackage package_1;
import java.util.ArrayList;
public class Snapshot {
// Modify the implementation of the Snapshot class so that an ArrayList stored
// in the snapshot is not affected by modifications to either the original or restored ArrayList.
private ArrayList<Integer> data;
public Snapshot(ArrayList<Integer> data) {
this.data = data;
}
public ArrayList<Integer> restore() {
return this.data;
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
Snapshot snap = new Snapshot(list);
list.set(0, 3);
list = snap.restore();
System.out.println(list); //It should log "[1,2]"
list.add(4);
list = snap.restore();
System.out.println(list); //It should log "[1,2]"
}
}
Blockquote
CodePudding user response:
You should read about Immutable Objects pattern https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
To make your Snapshot class work, it should:
- Make sure your list item is an Immutable class. Integer is the Immutable class.
- Copy all original list items to new list (snapshot data)
- Do not expose directly snapshot data reference to outside by return copying items instead
Source code:
public final class Snapshot {
private final List<Integer> data;
public Snapshot(List<Integer> data) {
this.data = new ArrayList<>(data);
}
public List<Integer> restore() {
return new ArrayList<>(this.data);
}
}
Main method:
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
Snapshot snap = new Snapshot(list);
list.set(0, 3);
System.out.println("It should log [3, 2], actual " list);
list = snap.restore();
System.out.println("It should log [1,2], actual " list);
list.add(4);
System.out.println("It should log [1,2, 4], actual " list);
list = snap.restore();
System.out.println("It should log [1,2], actual " list);
}
CodePudding user response:
package package_1;
import java.util.ArrayList;
public class Snapshot {
// Modify the implementation of the Snapshot class so that an ArrayList stored
// in the snapshot is not affected by modifications to either the original or restored ArrayList.
private ArrayList<Integer> data;
public Snapshot(ArrayList<Integer> list) {
data = new ArrayList<>(list);
}
public ArrayList<Integer> restore() {
return new ArrayList<>(data);
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
Snapshot snap = new Snapshot(list);
list.set(0, 3);
list = snap.restore();
System.out.println(list); //It should log "[1,2]"
list.add(4);
list = snap.restore();
System.out.println(list); //It should log "[1,2]"
}
}