Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator.

Similar presentations


Presentation on theme: "Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator."— Presentation transcript:

1 Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator iterator(); …} interface List extends Collection { … Iterator iterator(); Iterator iterator(); ListIterator listIterator(); ListIterator listIterator(); ListIterator listIterator(int index); ListIterator listIterator(int index); …} Interface Iterator { boolean hasNext() ; boolean hasNext() ; Object next() ; Object next() ; void remove() ; void remove() ;} Interface ListIterator extends Iterator { boolean hasNext() ; boolean hasNext() ; Object next() ; Object next() ; boolean hasPrevious() ; boolean hasPrevious() ; Object previous() ; Object previous() ; int nextIndex() ; int nextIndex() ; int previousIndex() ; int previousIndex() ; void remove() ; void remove() ; void set(Object o) ; void set(Object o) ; void add(Object o) ; void add(Object o) ;}

2 Java Iterator import java.util.*; public class IteratorExample { public static void main(String[] args) { public static void main(String[] args) { List ints = new ArrayList(); List ints = new ArrayList(); for(int i = 0; i < 10; i++) for(int i = 0; i < 10; i++) ints.add(new Integer(i)); ints.add(new Integer(i)); Iterator e = ints.iterator(); Iterator e = ints.iterator(); while(e.hasNext()) while(e.hasNext()) System.out.println( ((Integer)e.next()).intValue() ) ; System.out.println( ((Integer)e.next()).intValue() ) ; }}

3 Object Serialization

4 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 SerializeDeSerialize Frozen Object Stream Live Object

5 Serialization ObjectOutputStream & ObjectInputStream ObjectOutputStream & ObjectInputStream Works like other input-output streams Works like other input-output streams They can write and read Objects. They can write and read Objects. ObjectOutputStream: Serializes Java Objects into a byte-encoded format, and writes them onto an OutputStream. ObjectOutputStream: Serializes Java Objects into a byte-encoded format, and writes them onto an OutputStream. ObjectInputStream: Reads and reconstructs Java Objects from a byte- encoded format read from InputStream. ObjectInputStream: Reads and reconstructs Java Objects from a byte- encoded format read from InputStream. Serialization can be used in. Serialization can be used in. Remote Method Invocation (RMI), communication between objects via sockets. (Marshaling and unmarshaling objects) 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. Archival of an object for use in a later invocation of the same program. Objects to be serialized Objects to be serialized Must implement Serializable interface Must implement Serializable interface Non-persistent fields can be marked with transient keyword Non-persistent fields can be marked with transient keyword The following is written and read during serialization The following is written and read during serialization Class of the object Class of the object Class signature Class signature Values of all non-transient and non-static members Values of all non-transient and non-static members

6 Serialization To Write into an ObjectOutputStream 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 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() ;

7 Serialization ObjectOutputStream.writeObject(Object) traverses all the internal references of the object recursively and writes all of them. 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. ObjectOutputStream implements DataOutput interface to write primitive data types. writeInt( … ), writeFloat( … ), writeUTF( … ), etc. ObjectInputStream implements DataInput interface ro read primitive data types. ObjectInputStream implements DataInput interface ro read primitive data types. readInt(), readFloat(), readUTF(), etc. writeObject(Object) throws NotSerializableException if Object does not implement Serializable interface writeObject(Object) throws NotSerializableException if Object does not implement Serializable interface

8 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) ; }}}

9 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 ; }}

10 Customizing Serialization To define writeObject() and readObject() to append additional information. 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 }

11 Externalizable interface To control the serialization process explicitly, Externalizable interface must be implemented. To control the serialization process explicitly, Externalizable interface must be implemented. Externalizable interface 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. writeExternal and readExternal must save/load the state of the object. They must explicitly coordinate with its supertype to save its state.

12 General Programming Tips

13 Try to write self-documented programs: Try to write self-documented programs: Use logical variable names and function names : not : int x; but : int studentCount; Use logical variable names and function names : not : int x; but : int studentCount; Comments 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 Coding Conventions Class names start with Capital Class names start with Capital class MyClass { class MyClass { Instance names, fields, function names start with lower, etc. Instance names, fields, function names start with lower, etc. Object myObject ; Object myObject ; int myInt ; int myInt ; void myFunc() { … void myFunc() { … Static Final variables are All-Capitalized Static Final variables are All-Capitalized static final MAXVALUE = 200 ; static final MAXVALUE = 200 ; Necessary Tabs and spaces in Blocks. (Theoretically you can write a long program in a single line) Necessary Tabs and spaces in Blocks. (Theoretically you can write a long program in a single line)

14 General Programming Tips Use getter, setter, and is methods. Use getter, setter, and is methods. int getCount() ; int getCount() ; int setCount() ; int setCount() ; isEmpty() ; isEmpty() ; Self-checking classes Self-checking classes Use main() almost in every class to check class functionality. 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. You can make an expected output check, in order to verify changes in the class.

15 General Programming Tips In highly coupled classes, consider to make inner classes. In highly coupled classes, consider to make inner classes. Keep method definitions and scopes as short as possible. (For easy visualization and readability.) Keep method definitions and scopes as short as possible. (For easy visualization and readability.) Compiler-time errors are better then run time errors. Compiler-time errors are better then run time errors. Prefer Interface definition to Abstract Class Prefer Interface definition to Abstract Class Not : abstract class X { abstract void f() ; } Not : abstract class X { abstract void f() ; } But : interface X { void f() ; But : interface X { void f() ; Spelling problems in overriding Classes Spelling problems in overriding Classes class X { void encode() { … } } class X { void encode() { … } } class Y extends X { void Encode() { … } } // Does not overload the method class Y extends X { void Encode() { … } } // Does not overload the method Use Java Container Library classes Use Java Container Library classes List l = new ArrayList() ; List l = new ArrayList() ; Map hm = new HashMap() ; Map hm = new HashMap() ; Set s = new HashSet() ; Set s = new HashSet() ; List myStack = new LinkedList() ; List myStack = new LinkedList() ;

16 Debugging a program Handle Exceptions in their proper level. try { … } catch (Throwable) { … } // Bad Handle Exceptions in their proper level. try { … } catch (Throwable) { … } // Bad Don ’ t output errors to System.out, but to System.err 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) … } 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) … }


Download ppt "Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator."

Similar presentations


Ads by Google