Transcript serialize
Java Iterators
interface Collection {
…
Iterator iterator();
…
}
Interface Iterator {
boolean hasNext() ;
Object next() ;
void remove() ;
}
interface Set extends Collection {
…
Iterator iterator();
…
}
Interface ListIterator extends Iterator {
boolean hasNext() ;
Object next() ;
boolean hasPrevious() ;
Object previous() ;
int nextIndex() ;
int previousIndex() ;
void remove() ;
void set(Object o) ;
void add(Object o) ;
}
interface List extends Collection {
…
Iterator iterator();
ListIterator listIterator();
ListIterator listIterator(int index);
…
}
Java Iterator
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
List ints = new ArrayList();
for(int i = 0; i < 10; i++)
ints.add(new Integer(i));
Iterator e = ints.iterator();
while(e.hasNext())
System.out.println( ((Integer)e.next()).intValue() ) ;
}
}
Object Serialization
Object Serialization
To represent an object in a byte-encoded
format that can be stored and passed to a
stream, and in need can be reconstructed.
Live Object
Live Object
Frozen Object Stream
Serialize
DeSerialize
Serialization
ObjectOutputStream & ObjectInputStream
Serialization can be used in.
Remote Method Invocation (RMI), communication between objects via
sockets. (Marshaling and unmarshaling objects)
Archival of an object for use in a later invocation of the same program.
Objects to be serialized
Works like other input-output streams
They can write and read Objects.
ObjectOutputStream: Serializes Java Objects into a byte-encoded
format, and writes them onto an OutputStream.
ObjectInputStream: Reads and reconstructs Java Objects from a byteencoded format read from InputStream.
Must implement Serializable interface
Non-persistent fields can be marked with transient keyword
The following is written and read during serialization
Class of the object
Class signature
Values of all non-transient and non-static members
Serialization
To Write into an ObjectOutputStream
FileOutputStream out = new FileOutputStream(“afile”) ;
ObjectOutputStream oos = new ObjectOutputStream(out) ;
oos.writeObject(“Today”) ;
oos.writeObject(new Date()) ;
oos.flush() ;
To Read from an ObjectInputStream
FileInputStream in = new FileInputStream(“afile”) ;
ObjectInputStream ois = new ObjectInputStream(in) ;
String today = (String) ois.readObject() ;
Date date = (Date) ois.readObject() ;
Serialization
ObjectOutputStream.writeObject(Object)
traverses all the internal references of the object
recursively and writes all of them.
ObjectOutputStream implements DataOutput
interface to write primitive data types.
writeInt(…), writeFloat(…), writeUTF(…), etc.
ObjectInputStream implements DataInput
interface ro read primitive data types.
readInt(), readFloat(), readUTF(), etc.
writeObject(Object) throws
NotSerializableException if Object does not
implement Serializable interface
Object Serialization Example
import java.io.* ;
import java.util.* ;
class A implements Serializable {
public int i = 5 ;
public String str = "Hi" ;
public List l = new ArrayList() ;
}
public class ObjSerTest {
public static void main(String[]args) {
A a = new A() ;
a.i = 10 ; a.str = "Hello" ;
a.l.add("One") ; a.l.add("Two") ;
serialize(a) ;
}
private static void serialize(A a) {
System.out.println("Serializing...");
try {
FileOutputStream fos = new FileOutputStream("test.out") ;
ObjectOutputStream oos = new ObjectOutputStream(fos) ;
oos.writeObject(a) ;
} catch (Exception e) {
System.err.println("Problem: "+e) ;
}
}
}
Object De-serialization Example
import java.io.* ;
import java.util.* ;
class A implements Serializable {
public int i = 5 ;
public String str = "Hi" ;
public List l = new ArrayList() ;
}
public class ObjDeSerTest {
public static void main(String[]args) {
A a = deserialize() ;
System.out.println(a.i) ;
System.out.println(a.str) ;
System.out.println(a.l) ;
}
private static A deserialize() {
System.out.println("DeSerializing...");
try {
FileInputStream fis = new FileInputStream("test.out") ;
ObjectInputStream iis = new ObjectInputStream(fis) ;
return (A) iis.readObject() ;
} catch (Exception e) {
System.err.println("Problem: "+e) ;
}
return null ;
}
}
Customizing Serialization
To define writeObject() and readObject() to append
additional information.
private void writeObject(ObjectOutputStream oos) throws
IOException {
oos.defaultWriteObject() ;
// customized serialization code
}
private void readObject(ObjectInputStream ois) throws
IOException {
ois.defaultReadObject() ;
// customized deserialization code
// if necessary, must include code to update the object
}
Externalizable interface
To control the serialization process explicitly,
Externalizable interface must be implemented.
Externalizable interface
public interface Externalizable extends Serializable {
public void writeExternal(ObjectOutput out) throws IOException
;
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException ;
}
writeExternal and readExternal must save/load the state
of the object. They must explicitly coordinate with its
supertype to save its state.
General Programming Tips
General Programming Tips
Try to write self-documented programs:
Use logical variable names and function names :
not : int x;
but : int studentCount;
Comments
Use comments whenever something is unclear. Think that you are telling some other
person about your code. (After a long time, this person might be you)
Coding Conventions
Class names start with Capital
Instance names, fields, function names start with lower, etc.
Object myObject ;
int myInt ;
void myFunc() { …
Static Final variables are All-Capitalized
class MyClass {
static final MAXVALUE = 200 ;
Necessary Tabs and spaces in Blocks. (Theoretically you can write a long
program in a single line)
General Programming Tips
Use getter, setter, and is methods.
int getCount() ;
int setCount() ;
isEmpty() ;
Self-checking classes
Use main() almost in every class to check class
functionality.
You can make an expected output check, in order to
verify changes in the class.
General Programming Tips
In highly coupled classes, consider to make inner classes.
Keep method definitions and scopes as short as possible. (For easy
visualization and readability.)
Compiler-time errors are better then run time errors.
Prefer Interface definition to Abstract Class
Spelling problems in overriding Classes
Not : abstract class X { abstract void f() ; }
But : interface X { void f() ;
class X { void encode() { … } }
class Y extends X { void Encode() { … } }
Use Java Container Library classes
List l = new ArrayList() ;
Map hm = new HashMap() ;
Set s = new HashSet() ;
List myStack = new LinkedList() ;
// Does not overload the method
Debugging a program
Handle Exceptions in their proper level.
try { … } catch (Throwable) { … } // Bad
Don’t output errors to System.out, but to System.err
For Debugging code use a single global boolean variable
showing the Debug mode.
bDebug = true ; …
if (bDebug) { // Print some information
Care must be taken not to change any state inside.
if (bDebug) { if (i++==0) … }