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

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

Chapter 19 Binary I/O.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Serialization Flatten your object for automated storage or network.
Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.
Chapter - 12 File and Streams (continued) This chapter includes -  DataOutputStream  DataInputStream  Object Serialization  Serializing Objects 
Lecture 31 File I/O -Part 2 COMP1681 / SE15 Introduction to Programming.
Head-First Design Patterns. Similar to a ReminderEntry.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
Unit 201 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Java and C++, The Difference An introduction Unit - 00.
More on Inheritance Dr. Andrew Wallace PhD BEng(hons) EurIng
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
The Java Programming Language
1 7.0 Input-output in Java : Overview Introduction: It would be quite impossible for any program to do anything useful without performing some kind of.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java I/O Writing and Reading Objects to File Serialization.
Working with files. RHS – SOC 2 Motivation All our programs so far have only worked with data stored in primary storage (RAM) Data is lost when program.
Object Persistence and Object serialization CSNB534 Asma Shakil.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Serialization CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
Chapter 11 Exceptions and Input/Output Operations.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
Files and Serialization. Files Used to transfer data to and from secondary storage.
CSE 1020: Exceptions and A multiclass application Mark Shtern 1-1.
File Input & Output1 Streams & File I/O. Introduction (1) The Java platform includes a number of packages that are concerned with the movement of data.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
Java Programming: Advanced Topics 1 Input/Output and Serialization.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Object Writing in files
Memento Design Pattern
Chapter 17 Binary I/O 1.
Accessing Files in Java
File.
File I/O & collection frame work
Java Serialization B.Ramamurthy 11/8/2018 B.Ramamurthy.
Client server programming
Programming in Java Files and I/O Streams
CS 116 Object Oriented Programming II
Java Serialization B.Ramamurthy 11/14/2018 B.Ramamurthy.
Introduction to Java Programming
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
Command Invocation Protocol
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Podcast Ch23f Title: Serialization
The command invocation protocol
OO Java Programming Input Output.
Presentation transcript:

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

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

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

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

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

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

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

General Programming Tips

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)

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.

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

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) … }