Generalized Containers CSIS 3701: Advanced Object Oriented Programming.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
CS 106 Introduction to Computer Science I 04 / 30 / 2007 Last lecture :( Instructor: Michael Eckmann.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
For use of Cleveland State's IST410 Students only 1 Vectors and Collections.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
25-Jun-15 Vectors. 2 Vectors and arrays A Vector is like an array of Object s Differences between arrays and Vector s: Arrays have special syntax; Vector.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Vectors. Vectors and arrays A Vector is like an array of Object s Differences between arrays and Vector s: –Arrays have special syntax; Vector s don’t.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Copyright © Texas Education Agency, Advanced Computer Programming Data Structures: Collections.
CS 106 Introduction to Computer Science I 04 / 25 / 2007 Instructor: Michael Eckmann.
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
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
CS/ENGRD 2110 SPRING 2015 Lecture 6: Consequence of type, casting; function equals 1.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Lists and the Collection Interface Review inheritance & collections.
Chapter 18 Java Collections Framework
Computer Science 209 Software Development Java Collections.
Data structures Abstract data types Java classes for Data structures and ADTs.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CS 106 Introduction to Computer Science I 04 / 25 / 2008 Instructor: Michael Eckmann.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Generics CompSci 230 S Software Construction.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Object-Oriented Programming (Java) Review Unit 1 Class Design Basic Console I/O StringTokenizer Exception UML class diagram.
C19: Collection Classes (don’t forget to look at all the online code examples)
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Object Oriented Programming in Java Habib Rostami Lecture 7.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
CS/ENGRD 2110 SPRING 2016 Lecture 6: Consequence of type, casting; function equals 1.
Inheritance and Encapsulation
COP 3503 FALL 2012 Shayan Javed Lecture 8
Sorry these slides weren’t available last evening!
TCSS 143, Autumn 2004 Lecture Notes
ArrayLists.
Programming in Java Lecture 11: ArrayList
Lecture 26: Advanced List Implementation
Grouped Data Arrays, and Array Lists.
ArrayLists 22-Feb-19.
Collections Framework
JCF Collection classes and interfaces
ArrayLists 27-Apr-19.
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

Generalized Containers CSIS 3701: Advanced Object Oriented Programming

Generalizing Containers Example: Stack class that stores strings public class Stack { private String[] contents; private int top; public Stack(int s) { contents = new String[s]; top = 0; } public void push(String x) {contents[top++] = x;} public String pop() {return contents[--top];}

Generalizing Containers Problem: Need different stack class for different types of contents public class IntStack { private Integer[] contents; … public class EmployeeStack { private Employee[] contents; …

Generalizing Containers Goal: one stack class that can store any type of contents public class Stack { private anything[] contents; Tools: –Polymorphism: Can assign subclass object to superclass variable –Java hierarchy: All Java objects have Object class as ultimate superclass Key: Can assign any Java object to a variable of type Object

Containers of Objects Use Object as type stored by container public class Stack { private Object[] contents; private int top; public Stack(int s) { contents = new Object[s]; top = 0; } public void push(Object x) {contents[top++] = x;} public Object pop() {return contents[--top];}

Containers of Objects Example: Stack stooges = new Stack(4); Stooges.push(“Larry”); Stooges.push(“Curley”); Stooges.push(“Moe”); public class Stack { public void push(Object x) {contents[top++] = x;} private Object[] contents; Storing String objects in Object array

Limits of Containers of Objects Inspector methods return Object type instead of original type stored Will cause error if assigned to variable of original type stooges.push(“Moe”); String name = stooges.pop(); Must explicitly cast back to original type: String name = (String)stooges.pop(); Object Type mismatch error!

Limits of Containers of Objects Cannot store simple types in containers –Store in type wrappers stooges.push(new Integer(3)); –Is done automatically by later versions of Java Can store multiple types of object in single container stooges.push(“Larry”); stooges.push(3); stooges.push(new Clock()); –Problem if must cast back to original type – what was it?

Java Container Classes Java provides many built-in generalized containers –Stack, Queue, Hashtable, … –In java.util.* All implemented by storing Object elements Most used container type: ArrayList –Can access elements by index (like array) –Can insert/remove elements (like linked list) –Can grow dynamically (like linked list) –Has built-in search

ArrayList Class “Array” type methods: –public void set(int index, Object x); store x in index th element –public Object get(int index); return object at index th element Will need to cast back to original type Throws ArrayIndexOutOfBoundsException if index illegal –public int size();

ArrayList Class “Linked list” type methods: –public void add(Object x); add x to end of list –public void add(int index, Object x); insert x at index th element (shifting others to right) –public Object remove(int index); remove object at index th element (shifting others to left) and return it

ArrayList Class “Search” type methods: –public boolean contains(Object x); returns true if x in list –public void indexOf(Object x); return index of first occurrence of x (or -1 if x not in list) –public void indexOf(Object x, int index); return index of first occurrence of x starting at index Based on equals method for object x

ArrayList Example Rewrite of NameList to use ArrayList –no maximum since list grows dynamically –no current, since can add dynamically to end public class NameList { private ArrayList names; // List of names stored public NameList() { names = new ArrayList(); }

ArrayList Example Use “linked list” method to add new name to end Use search to make sure not already in list public void add(String name) throws InListException { if (names.contains(name)) throw new InListException(); names.add(name); } Use “array” method to iterate through list (casting back to original type) public String toString() { String result = ""; for (int i = 0; i < names.size(); i++) result += (String)names.get(i)+","; return result; }

Object Equality Java containers use equals method for search public boolean contains(Object x) { for (int i = 0; i < size(); i++) if x.equals(get(i)) return true; return false; May need to override equals in your classes if –Store in container –Search for equivalent objects (perhaps to avoid duplication) Will need to define what it means for two objects to be “equivalent”

Object Equality Built-in equals method takes an Object as parameter –Must check type of parameter first using instanceof operator –Then cast to appropriate type before comparing relevant fields Basic form of a equals method for some class C: public boolean equals(Object x) { if (this == x) return true; if (x instanceof C) { C y = (C)x; compare relevant fields, returning either true or false } return false; } Do they refer to the same object? Is it the same type as C? If so, cast to class C and compare relevant fields

Object Equality Example: equals for Employee class –Define as equivalent if have same name public boolean equals(Object x) { if (this == x) return true; if (x instanceof Employee) { Employee e = (Employee)x; return name.equals(e.name); } return false; }

Generics (Templates) Containers with type checking –Define generically: stores object of “type ” public class classname {… –Define the actual type when specific object created classname variable = new classname(); –Originated by C++ –Recently implemented (in limited form) in Java

Defining Generics Example: Pair class –Stores two different values of same type –Type determined when object constructed public class Pair { private T thing1, thing2; public Pair() { thing1 = thing2 = null; } Stores two variables, both of type T

Defining Generics public class Pair { … public void set(T value, int which) { if (which == 1) thing1 = value; if (which == 2) thing2 = value; } public T get(int which) { if (which == 1) return thing1; if (which == 2) return thing2; return null; } Methods take/return values of generic type T

Using Generics Define actual type stored when object declared Pair p1 = new Pair(); p1.set("Fred", 1); p1.set("Barney", 2); String name = p1.get(1); Note that do not need to cast back to original type – compiler now knows original type

Using Generics Can create generics of different types Pair p2 = new Pair(); p2.set(12, 1); p2.set(13, 2); int x = p2.get(1); p2.set(“Fred”, 1); Unlike polymorphism, Java does type checking

Limits of Generics Java does not allow arrays to be used with generics –This is legal in C++! public class StackTemplate { private T[] contents; private int top; public StackTemplate(int s) { contents = new T[s]; top = 0; Compiler error

Generics and Java Containers Many Java containers upgraded to use generics Example: Vector class ArrayList a = new ArrayList(); a.add(“Larry”); a.add(3); ArrayList that only contains Strings This is legal This is not

Generics and Java Containers Can use generic containers to define your own containers –Example: Generic Stack class that uses generic ArrayList class public class StackTemplate { private ArrayList contents; public StackTemplate() {contents = new ArrayList();} public void push(T x) {contents.add(x);} public T pop() { return contents.remove(contents.size()-1); } }