Cloning.  Goal: Create an identical, independent copy of an object  Override the method (every class inherits clone() from class Object) public Object.

Slides:



Advertisements
Similar presentations
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
Advertisements

Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
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++)
Java Review Interface, Casting, Generics, Iterator.
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
CHAPTER 4 Queues. Queue  The queue, like the stack, is a widely used data structure  A queue differs from a stack in one important way  A stack is.
CHAPTER 4 Queues MIDTERM THURSDAY, OCTOBER 17 IN LAB.
Computer Science 209 Software Development Iterators.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Chapter 3 Collection Classes Anshuman Razdan Department of Engineering
Tirgul 1 Today’s subjects: –First programming exercise. –Java reminder & completions : reference data types, cloning, inner classes, packages. –Short reminder.
Mutable, Immutable, and Cloneable Objects Chapter 15.
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
CST Razdan et al Razdan with contribution from others 1 Chapter 6 Stacks Anshuman Razdan Div of Computing.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
Stacks, Queues, and Deques
Stacks, Queues, and Deques
16-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Interfaces, Copying/Cloning,
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
08 1 Abstract Data Types Problem Sets: PS2 due due Monday, Feburary 26 PS3 due Wednesday, March 7 Wellesley College CS230 Lecture 08 Monday, February 26.
Abstract and Nested Classes
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Information and Computer Sciences University of Hawaii, Manoa
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
C++ STL CSCI 3110.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Chapter Objectives  Learn how to represent a waiting line (queue)  Become proficient using the methods in the Queue  Understand how to implement the.
Advanced Java Programming CS 537 – Data Structures and Algorithms.
Does not implement clone() method! public class Bar { … public Object clone() { … } Does not implement Cloneable interface!
Computer Science 209 The Factory Pattern. Collections and Iterators List list1 = new ArrayList (); List list2 = new LinkedList (); Set set1 = new HashSet.
Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
CS2852 Week 3, Class 2 Today Stacks Queues SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
Computer Science 209 Software Development Inheritance and Composition.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Data Structures David Kauchak cs302 Spring Data Structures What is a data structure? Way of storing data that facilitates particular operations.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
CS-2851 Dr. Mark L. Hornick 1 Stacks and Queues Behavior vs. Structure.
Click to edit Master text styles Stacks Data Structure.
Marcus Biel, Software Craftsman
Software Development Iterators
CSE 331 Cloning objects slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Programming in Java Lecture 11: ArrayList
CSE 1030: Data Structure Mark Shtern.
CSE 214 – Computer Science II Stacks
Stacks public interface Stack { public boolean empty();
Chapter 4 Queues.
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Java Programming Language
Introduction to Stacks
Lecture 16 Stacks and Queues CSE /26/2018.
Presentation transcript:

Cloning

 Goal: Create an identical, independent copy of an object  Override the method (every class inherits clone() from class Object) public Object clone()  General Setup: 1. State the the class implements Cloneable 2. Implement the method public Object clone() a) create a copy by calling the parent’s clone method b) clone the data members c) return the copy Cloning

class MyClass implements Cloneable {... data members of MyClass... public Object clone() { try { MyClass copy = (MyClass) super.clone();... copy/clone the data members... return copy } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; }

Clone and Constructor Similarity class Explorer extends Robot { private int points; private Location target; public Explorer(int m, int r, int c) { super(m, r, c); points = 0; target = new Location(random(), random()); } public Object clone() { Explorer copy = (Explorer) super.clone(); copy.points = this.points; copy.target = (Location) this.target.clone(); return copy; }

 Example class to illustrate Aliasing, Shallow Copy, Deep Copy: class Robot { private int model; private Location location; // the class methods } Cloning

Robot r1 = new Robot(123, 5, 6); Robot r2 = r1; Aliasing (not Cloning) model: 123 location: row: 5 col: 5 r1 r2 r2 is just another name for (another way to reference) the Robot r1.

model: 123 location: row: 5 col: 6 r1 r2 model: 123 location: Shallow Copy (did not clone the data members) public Object clone() { Robot copy = (Robot) super.clone(); copy.model = this.model; copy.location = this.location; return copy; } Robot r1 = new Robot(123, 5, 6); Robot r2 = (Robot) r1.clone();

model: 123 location: row: 5 col: 6 r1 r2 model: 123 location: Deep Copy (cloned the data members) public Object clone() { Robot copy = (Robot) super.clone(); copy.model = this.model; copy.location = (Location) this.location.clone(); return copy; } Robot r1 = new Robot(123, 5, 6); Robot r2 = (Robot) r1.clone(); row: 5 col: 6

Data Structures

 Special purpose structures used for organizing and managing data  Provide controlled access to the stored data  Tradeoffs in efficiency in storing and accessing the data (CS III)  Examples: ArrayList-- one-dimensional “array” MyGrid-- two-dimensional “array” (hw 5) Stack-- last in, first out (LIFO) Queue-- first in, first out (FIFO) Data Structures

Inheritance vs Composition

 Implementation that uses Inheritance ? class Stack extends ArrayLits { public E pop() { return remove(size()-1); } public E peek() { return get(size()-1); } public void push(E elmnt) { add(elmnt); } }  The methods clear(), empty(), size() come for free (inherited)  Unfortunately, Stack acquires other methods that affect Stack integrity Data Structures Implementation (Inheritance vs Composition)

 Implementation that uses Composition ? class Stack { private ArrayLits items; public E pop() { return items.remove(size()-1); } public E peek() { return items.get(size()-1); } public void push(E elmnt) { items.add(elmnt); } public int size() { return items.size(); } public void clear() { items.clear(); } public boolean empty() { return items.isEmpty();} } Data Structures Implementation (Inheritance vs Composition)

 Composition should be used !  A bit more work – have to implement clear(), empty(), size()  However, Stack integrity is preserved, i.e. only the methods required by Stack are available to the user (with Inheritance user got extra methods that can “damage” the Stack) Data Structures Implementation (Inheritance vs Composition)

Iterators, Enhanced for-loop

 Iterators generalize the concept of traversing a collection  Uni-direction Iterator has the following interface boolean hasNext() -- are there more elements to traverse E next() -- return next element in collection void remove() -- remove last returned item (optional) Iterators

Using Iterators  See reference files Stack.java and IteratorTester.java for Assignment 12 // option 1: standard CS I traversal for (int i = 0; i < numbers.size(); i++) { Double value = numbers.get(i); System.out.println("1.processing: " + value); } // option 2: extract an iterator object Iterator iter = numbers.iterator(); while( iter.hasNext() ) { Double value = iter.next(); System.out.println("2.processing: " + value); } // option 3: a convenient form for option 2 for (Double value : numbers) { System.out.println("3.processing: " + value); }

Implementing Iterators class Stack implements Iterable {... Stack methods and data members... // required by Iterable interface – return an Iterator object Iterator iterator() { Iterator iter = new StackIterator (); return iter; } // internal class that manages the iteration though the Stack class StackIterator implements Iterator { private int index; // point to current element public StackIterator() { initialize the iterator } public boolean hasNext() { check if index in range } public E next() { return current element; update index } public void remove() { throw exception if no action on remove} }

The “Rookie Mistakes”

class Command { private Canvas canvas; private Shape shape; public Command(Canvas c, Shape s) { Canvas canvas = c; Shape shape = s; } } “Rookie Mistakes”

class Command { private Canvas canvas; private Shape shape; public Command(Canvas c, Shape s) { Canvas canvas = c; Shape shape = s; } } “Rookie Mistakes”

class Command { private Canvas canvas; private Shape shape; public Command(Canvas c, Shape s) { c = canvas; s = shape; } } “Rookie Mistakes”

class Command { private Canvas canvas; private Shape shape; public Command(Canvas c, Shape s) { c = canvas; canvas = c; s = shape; shape = s; } } “Rookie Mistakes”

class Command { private Canvas canvas; private Shape shape; } class MoveCommand extends Command { private Canvas canvas; private Shape shape; private int dx; private int dy; } “Rookie Mistakes”

class Command { private Canvas canvas; private Shape shape; } class MoveCommand extends Command { private Canvas canvas; private Shape shape; private int dx; private int dy; } “Rookie Mistakes”

class MoveCommand extends Command { private int dx; private int dy; public MoveCommand(Canvas c, Shape s, ind dx, int dy) { super(c, s); dx = dx; dy = dy; } } “Rookie Mistakes”

class MoveCommand extends Command { private int dx; private int dy; public MoveCommand(Canvas c, Shape s, ind dx, int dy) { super(c, s); this.dx = dx; this.dy = dy; } } “Rookie Mistakes”

THE END sides face roll getFace getSides