Lecture 4 Flashcards
What is aliasing?
Having a variable refer to an existing object
How does Object.clone() work?
All primitive fields are copied
All Object fields are aliased, i.e. refer to the old ones
What interface must objects implement to allow cloning?
Cloneable
Why do you have to be careful with cloning an object that contains mutable fields?
whats the solution?
Changes to mutable fields will change in every object clone
Solution: clone the mutable field during cloning of the object
How are objects serialised using Object streams?
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(“bank.dat”));
out.writeObject(b);
…
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“bank.dat”));
BankAccount b = (BankAccount)(in.readObject());
What can readObject() throw?
ClassNotFoundException and IOException
Why do you have to be careful serialising objects?
All object fields will also be serialised
So many many objets might be serialised from one call - potential massive files
How can a class be marked as Serialisable?
Implement interface Serializable
how to you prevent field being serialised?
Mark it as transient
If the same object is serialised twice in one ObjectOutputStream, what happens?
Assigned a serial number and second serialisation just prints that out.
What is the version problem?
How is it generally solved?
If the structure of a class changes between serialisation and deserialisation
Give null or empty values to new fields
Why is a BufferedReader better than calling Paths.readAllLines(path)
readAllLines reads entire file into memory
BufferedReader goes line by line
what is a potential problem with buffered streams?
May have to explicitly flush them
How do you format a number?
System.out.format(“sqrt(%d) = %.8f%n”, i, r);
// sqrt(2) = 1.41421356
.8 means 8 digits after decimal point
what is GSON?
Open source library to convert Java objects to and from JSON