java iterators interface collection { … iterator iterator(); iterator iterator(); …} interface...

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

Post on 20-Dec-2015

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Java IteratorsJava Iteratorsinterface Collectioninterface Collection{ {

… … Iterator iteratorIterator iterator;)(;)(

… … }}

interface Set extends Collectioninterface Set extends Collection{ { … …

Iterator iteratorIterator iterator;)(;)(… … }}

interface List extends Collectioninterface List extends Collection{ { … …

Iterator iteratorIterator iterator;)(;)( ListIterator listIteratorListIterator listIterator;)(;)(

ListIterator listIterator(int index)ListIterator listIterator(int index);;… … }}

Interface IteratorInterface Iterator{ { boolean hasNextboolean hasNext; )(; )(

Object nextObject next; )(; )( void removevoid remove; )(; )(

}}

Interface ListIterator extends IteratorInterface ListIterator extends Iterator {{

boolean hasNextboolean hasNext; )(; )( Object nextObject next; )(; )(

boolean hasPreviousboolean hasPrevious; )(; )( Object previousObject previous; )(; )(

int nextIndexint nextIndex; )(; )( int previousIndexint previousIndex; )(; )(

void removevoid remove; )(; )( void set(Object o)void set(Object o); ; void add(Object o)void add(Object o); ;

}}

Page 2: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Java IteratorJava Iterator

import java.util.*; import java.util.*; public class IteratorExample { 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() ) ; } } }}

Page 3: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Object SerializationObject Serialization

Page 4: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Object SerializationObject Serialization

To represent an object in a byte-To represent an object in a byte-encoded format that can be stored encoded format that can be stored

and passed to a stream, and in need and passed to a stream, and in need can be reconstructedcan be reconstructed..

Live Object

Serialize DeSerialize

Frozen Object Stream Live Object

Page 5: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

SerializationSerialization ObjectOutputStream & ObjectInputStreamObjectOutputStream & ObjectInputStream

Works like other input-output streamsWorks like other input-output streams They can write and read Objects.They can write and read Objects. ObjectOutputStream: Serializes Java Objects into a byte-ObjectOutputStream: Serializes Java Objects into a byte-

encoded format, and writes them onto an OutputStream.encoded format, and writes them onto an OutputStream. ObjectInputStream: Reads and reconstructs Java Objects from ObjectInputStream: Reads and reconstructs Java Objects from

a byte-encoded format read from InputStream.a byte-encoded format read from InputStream.

Serialization can be used in.Serialization can be used in. Remote Method Invocation (RMI), communication between Remote Method Invocation (RMI), communication between

objects via sockets. (Marshaling and unmarshaling objects)objects via sockets. (Marshaling and unmarshaling objects) Archival of an object for use in a later invocation of the same Archival of an object for use in a later invocation of the same

program.program.

Objects to be serialized Objects to be serialized Must implement Must implement SerializableSerializable interface interface Non-persistent fields can be marked with Non-persistent fields can be marked with transient transient keywordkeyword

The following is written and read during serializationThe following is written and read during serialization Class of the objectClass of the object Class signatureClass signature Values of all non-transient and non-static membersValues of all non-transient and non-static members

Page 6: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

SerializationSerialization

To Write into an ObjectOutputStreamTo Write into an ObjectOutputStreamFileOutputStream out = new FileOutputStream(“afile”) ;FileOutputStream out = new FileOutputStream(“afile”) ;ObjectOutputStream oos = new ObjectOutputStream oos = new ObjectOutputStream(out) ;ObjectOutputStream(out) ;oos.writeObject(“Today”) ;oos.writeObject(“Today”) ;oos.writeObject(new Date()) ;oos.writeObject(new Date()) ;oos.flush() ;oos.flush() ;

To Read from an ObjectInputStreamTo Read from an ObjectInputStreamFileInputStream in = new FileInputStream(“afile”) ;FileInputStream in = new FileInputStream(“afile”) ;ObjectInputStream ois = new ObjectInputStream(in) ;ObjectInputStream ois = new ObjectInputStream(in) ;String today = (String) ois.readObject() ;String today = (String) ois.readObject() ;Date date = (Date) ois.readObject() ;Date date = (Date) ois.readObject() ;

Page 7: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

SerializationSerialization

ObjectOutputStream.writeObject(Object) ObjectOutputStream.writeObject(Object) traverses all the internal references of the traverses all the internal references of the object recursively and writes all of them.object recursively and writes all of them.

ObjectOutputStream implements ObjectOutputStream implements DataOutput interface to write primitive DataOutput interface to write primitive data types.data types.writeInt(…), writeFloat(…), writeUTF(…), etc.writeInt(…), writeFloat(…), writeUTF(…), etc.

ObjectInputStream implements DataInput ObjectInputStream implements DataInput interface ro read primitive data types.interface ro read primitive data types.readInt(), readFloat(), readUTF(), etc.readInt(), readFloat(), readUTF(), etc.

writeObject(Object) throws writeObject(Object) throws NotSerializableException if Object does not NotSerializableException if Object does not implement Serializable interfaceimplement Serializable interface

Page 8: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Object Serialization ExampleObject Serialization Exampleimport java.io.* ;import java.io.* ;import java.util.* ;import java.util.* ;class A implements Serializable {class A implements Serializable {

public int i = 5 ;public int i = 5 ;public String str = "Hi" ;public String str = "Hi" ;public List l = new ArrayList() ;public List l = new ArrayList() ;

}}public class ObjSerTest {public class ObjSerTest {

public static void main(String[]args) {public static void main(String[]args) {A a = new A() ;A a = new A() ;a.i = 10 ; a.str = "Hello" ;a.i = 10 ; a.str = "Hello" ;a.l.add("One") ; a.l.add("Two") ;a.l.add("One") ; a.l.add("Two") ;serialize(a) ;serialize(a) ;

}}private static void serialize(A a) {private static void serialize(A a) {

System.out.println("Serializing...");System.out.println("Serializing...");try {try {

FileOutputStream fos = new FileOutputStream("test.out") ;FileOutputStream fos = new FileOutputStream("test.out") ;ObjectOutputStream oos = new ObjectOutputStream(fos) ;ObjectOutputStream oos = new ObjectOutputStream(fos) ;oos.writeObject(a) ;oos.writeObject(a) ;

} catch (Exception e) {} catch (Exception e) {System.err.println("Problem: "+e) ;System.err.println("Problem: "+e) ;

}}}}

}}

Page 9: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Object De-serialization Object De-serialization ExampleExampleimport java.io.* ;import java.io.* ;import java.util.* ;import java.util.* ;class A implements Serializable {class A implements Serializable {

public int i = 5 ;public int i = 5 ;public String str = "Hi" ;public String str = "Hi" ;public List l = new ArrayList() ;public List l = new ArrayList() ;

}}public class ObjDeSerTest {public class ObjDeSerTest {

public static void main(String[]args) {public static void main(String[]args) {A a = deserialize() ;A a = deserialize() ;System.out.println(a.i) ;System.out.println(a.i) ;System.out.println(a.str) ;System.out.println(a.str) ;System.out.println(a.l) ;System.out.println(a.l) ;

}}private static A deserialize() {private static A deserialize() {

System.out.println("DeSerializing...");System.out.println("DeSerializing...");try {try {

FileInputStream fis = new FileInputStream("test.out") ;FileInputStream fis = new FileInputStream("test.out") ;ObjectInputStream iis = new ObjectInputStream(fis) ;ObjectInputStream iis = new ObjectInputStream(fis) ;return (A) iis.readObject() ;return (A) iis.readObject() ;

} catch (Exception e) {} catch (Exception e) {System.err.println("Problem: "+e) ;System.err.println("Problem: "+e) ;

}}return null ;return null ;

}}}}

Page 10: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Customizing SerializationCustomizing Serialization

To define writeObject() and readObject() to To define writeObject() and readObject() to append additional information.append additional information.private void writeObject(ObjectOutputStream oos) throws private void writeObject(ObjectOutputStream oos) throws

IOException {IOException {oos.defaultWriteObject() ;oos.defaultWriteObject() ;// customized serialization code// customized serialization code

}}private void readObject(ObjectInputStream ois) throws private void readObject(ObjectInputStream ois) throws

IOException {IOException {ois.defaultReadObject() ;ois.defaultReadObject() ;// customized deserialization code// customized deserialization code// if necessary, must include code to update the object// if necessary, must include code to update the object

}}

Page 11: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Externalizable interfaceExternalizable interface

To control the serialization process explicitly, To control the serialization process explicitly, Externalizable interface must be implemented.Externalizable interface must be implemented.

Externalizable interfaceExternalizable interfacepublic interface Externalizable extends Serializable {public interface Externalizable extends Serializable {

public void writeExternal(ObjectOutput out) throws public void writeExternal(ObjectOutput out) throws IOException ;IOException ;public void readExternal(ObjectInput in) throws public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException ; IOException, ClassNotFoundException ;

}}

writeExternal and readExternal must save/load writeExternal and readExternal must save/load the state of the object. They must explicitly the state of the object. They must explicitly coordinate with its supertype to save its state.coordinate with its supertype to save its state.

Page 12: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

General Programming TipsGeneral Programming Tips

Page 13: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

General Programming TipsGeneral Programming Tips Try to write self-documented programs:Try to write self-documented programs:

Use logical variable names and function names : Use logical variable names and function names : not : int x; not : int x; but : int studentCount;but : int studentCount;

CommentsCommentsUse comments whenever something is unclear. Think that you are telling Use comments whenever something is unclear. Think that you are telling

some other person about your code. (After a long time, this person some other person about your code. (After a long time, this person might be you)might be you)

Coding ConventionsCoding Conventions Class names start with CapitalClass 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-CapitalizedStatic Final variables are All-Capitalized static final MAXVALUE = 200 ;static final MAXVALUE = 200 ;

Necessary Tabs and spaces in Blocks. (Theoretically you can write a Necessary Tabs and spaces in Blocks. (Theoretically you can write a long program in a single line)long program in a single line)

Page 14: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

General Programming TipsGeneral 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 classesSelf-checking classes Use main() almost in every class to check class Use main() almost in every class to check class

functionality.functionality. You can make an expected output check, in You can make an expected output check, in

order to verify changes in the class.order to verify changes in the class.

Page 15: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

General Programming TipsGeneral 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 Keep method definitions and scopes as short as possible. (For

easy visualization and readability.)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 ClassPrefer 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 ClassesSpelling problems in overriding Classes class X { void encode() { … } }class X { void encode() { … } } class Y extends X { void Encode() { … } } // Does not overload the class Y extends X { void Encode() { … } } // Does not overload the

methodmethod Use Java Container Library classesUse 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() ;

Page 16: Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator

Debugging a programDebugging a program

Handle Exceptions in their proper level.Handle Exceptions in their proper level.try { … } catch (Throwable) { … } // Badtry { … } catch (Throwable) { … } // Bad

Don’t output errors to System.out, but to Don’t output errors to System.out, but to System.errSystem.err

For Debugging code use a single global boolean For Debugging code use a single global boolean variable showing the Debug mode.variable showing the Debug mode.

bDebug = true ; …bDebug = true ; …if (bDebug) { // Print some informationif (bDebug) { // Print some information

Care must be taken not to change any state Care must be taken not to change any state inside.inside.

if (bDebug) { if (i++==0) … }if (bDebug) { if (i++==0) … }