1 / 16

Java Iterators

Java Iterators. interface Collection { … Iterator iterator(); … } interface Set extends Collection { … Iterator iterator(); … } interface List extends Collection { … Iterator iterator(); ListIterator listIterator(); ListIterator listIterator(int index); … }.

ermin
Download Presentation

Java Iterators

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Iterators interface Collection { … Iterator iterator(); … } interface Set extends Collection { … Iterator iterator(); … } interface List extends Collection { … Iterator iterator(); ListIterator listIterator(); ListIterator listIterator(int index); … } Interface Iterator { boolean hasNext() ; Object next() ; void remove() ; } 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) ; }

  2. 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() ) ; } }

  3. Object Serialization

  4. 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 Frozen Object Stream Live Object Serialize DeSerialize

  5. Serialization • ObjectOutputStream & ObjectInputStream • 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 byte-encoded format read from InputStream. • 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 • 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

  6. 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() ;

  7. 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

  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. • 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. • 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.

  12. General Programming Tips

  13. 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 • class MyClass { • Instance names, fields, function names start with lower, etc. • Object myObject ; • int myInt ; • void myFunc() { … • Static Final variables are All-Capitalized • static final MAXVALUE = 200 ; • 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. • 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.

  15. 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 • Not : abstract class X { abstract void f() ; } • But : interface X { void f() ; • Spelling problems in overriding Classes • class X { void encode() { … } } • class Y extends X { void Encode() { … } } // Does not overload the method • Use Java Container Library classes • List l = new ArrayList() ; • Map hm = new HashMap() ; • Set s = new HashSet() ; • List myStack = new LinkedList() ;

  16. 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 informationCare must be taken not to change any state inside. if (bDebug) { if (i++==0) … }

More Related