1/20/03A2-1 CS494 Interfaces and Collection in Java.

Slides:



Advertisements
Similar presentations
Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Concrete collections in Java library
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
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++)
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
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.
15-Jun-15 Lists in Java Part of the Collections Framework.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 17 Advanced Java Concepts Data Structure Support.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
05 - Containers DRAFT COPY © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
1 Frameworks Part 2. 2 Collections Framework Java API contains library of useful data structures Collections library also serves as framework for adding.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Chapter 19 Java Data Structures
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
CS2110: SW Development Methods
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
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.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
1 Java Collection: Data structure framework. 2 Background collections store and organize objects for efficient access Java collections: traditional data.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
©SoftMoore ConsultingSlide 1 Java Collections Framework.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1/20/05A-1 © 2001 T. Horton CS 494 Adv. SW Design and Development A Tasting…. Course 1: Design patterns: Intro, example Course 2: Inheritance, Interfaces,
1 Collections. 2 Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful.
Collections Dwight Deugo Nesa Matic
C19: Collection Classes (don’t forget to look at all the online code examples)
Object Oriented Programming in Java Habib Rostami Lecture 7.
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
CS 151: Object-Oriented Design December 3 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Using the Java Collection Libraries COMP 103 # T2
Implementing ArrayList Part 1
Collections in Java The objectives of this lecture are:
Collections Framework
Hashing in java.util
Java Generics & Iterators
Presentation transcript:

1/20/03A2-1 CS494 Interfaces and Collection in Java

1/20/03A2-2 Java Interfaces Note that the word “interface” –Is a specific term for a language contstruct –Is not the general word for “communication boundary” –Is also a term used in UML (but not in C++)

1/20/03A2-3 Why Use Inheritance? Why inherit? Create a class that… 1.Makes sense in problem domain 2.Locates common implementation in superclass 3.Defines a shared API (methods) so we can… 4.Use polymorphism Define a reference or parameter in terms of the superclass If just last two, then use Java interface –No shared implementation –You commit that part of what defines a class is that it meets a particular API –We can write methods etc. that operate on objects of any class that meets or supports that interface

1/20/03A2-4 Two Types of Inheritance How can inheritance support reuse? Implementation Inheritance –A subclass reuses some implementation from an ancestor –In Java, keyword extends Interface Inheritance –A “subclass” shares the interface with an “ancestor” –In Java, keyword implements –I.e. this class will support this set of methods

1/20/03A2-5 Interfaces and Abstract Classes Abstract classes: –Cannot create any instances Prefer Java interfaces over abstract classes! –Existing classes can add an interface –Better support for mix-in classes E.g. Comparable interface -- supports compare() –Do not need a hierarchical framework –Composition preferred over inheritance E.g. wrapper classes But, abstract classes have some implementation –Skeletal implementation classes, e.g. AbstractCollection Disadvantage: once released, a public interface shouldn’t be updated

1/20/03A2-6 Interfaces in Other Languages A modeling method in UML Interfaces in C++ –All methods are pure virtual –No data members –Use multiple inheritance

1/20/03A2-7 Collections in Java ADT: more than one implementation meets same interface, models same data In Java, separate interface from implementation We’ll illustrate with “fake” Java example: –Queue interface –Two implementations

1/20/03A2-8 Defining an Interface Java code: interface Queue { void add (Object obj); Object remove(); int size(); } Nothing about implementation here! –methods and no fields

1/20/03A2-9 Using Objects by Interface Say we had two implementations: Queue q1 = new CircularArrayQueue(100); or Queue q1 = new LinkedListQueue(); q1.add( new Widget() ); Queue q3 = new … Queue q2 = mergeQueue(q2, q3);

1/20/03A2-10 Implementing an Interface Example: class CircularArrayQueue implements Queue {CircularArrayQueue(int capacity) {…} public void add(Object o) {…} public Object remove() {…} public int size() {…} private Object[] elements; private int head; private int tail; }

1/20/03A2-11 Implementing an Interface (2) Implementation for LinkedListQueue similar Question: How to handle errors? –Array version is bounded. add() when full? –Throw an exception, perhaps –Not an issue for linked list version, though

1/20/03A2-12 Real Collection Interfaces in Java All collections meet Collection interface: boolean add(Object obj); Iterator iterator(); int size(); boolean isEmpty(); boolean contains(Object obj); boolean containsAll (Collection other); … See Java API documentation for all methods

1/20/03A2-13 Iterator Interface Three fundamental methods: Object next(); boolean hasNext(); void remove(); We use an iterator object returned by Collection.iterator() to visit or process items in the collection –Don’t really know or care how its implemented

1/20/03A2-14 Example Iterator Code Traverse a collection of Widgets and get each object Iterator iter = c.iterator(); while ( iter.hasNext() ) { Object obj = iter.next(); // or: Widget w = (Widget) iter.next(); // do something with obj or w } Note the cast!

1/20/03A2-15 Methods Defined by Other IF Methods Some collection methods can be defined “abstractly” public boolean addAll (Collection from) { Iterator iterFrom = from.iterator(); boolean modified = false; while ( iterFrom.hasNext() ) if ( add(iterFrom.next()) ) modified = true; return modified; }

1/20/03A2-16 Collections and Abstract Classes To define a new Collection, one must implement all methods -- a pain! Better: define a skeletal implementation class –Leaves primitives undefined: add(), iterator() –Defines other methods in terms of those Concrete collection class inherits from skeletal class –Defines “primitives” –Overrides any methods it chooses too Java library: AbstractCollection –Implements Collection IF –You inherit from it to roll your own Collection

1/20/03A2-17 Java’s Concrete Collection Classes Vector is like array but grows dynamically –Insertion or deletion in the middle expensive LinkedList class –Doubly-linked –Ordered collection add() inserts at end of list How do we add in middle?

1/20/03A2-18 ListIterator Interface ListIterator (sub)interface extends Iterator // add element before iterator position void add(Object o); // on ListIterator object Object previous(); boolean hasPrevious(); void set(Object o); int nextIndex(); and int previousIndex(); Also a factory that takes an initial position. E.g. ListIterator backIter = c.listIterator( c.size() ); Concurrent modification by two iterators? –ListIterator checks for this

1/20/03A2-19 ArrayList Collection Like a Vector but implements the List IF –Stores an array internally –Access to element by index is constant, O(1) –Element insertion/removal is W(n) = O(n) –Expansion automatic (but with time costs) Supports get(index) and set(index) –So does LinkedList but inefficient –Note: in Vector, elementAt() and setElementAt() Supports synchronization –Vector does not.

1/20/03A2-20 List Interface All methods from Collection interface, plus… int indexOf(Object elem) -- not found? -1 int lastIndexOf(Object elem) Object remove(int index) Object set(int index, Object elem) Object clone() -- makes a shallow copy List subList(int fromIndex, int toIndex)

1/20/03A2-21 Other ArrayList Methods Constructors: –default; given initial capacity; given Collection Capacity management: –void ensureCapacity(); void trimToSize(); Collection to array: –Object[] toArray();

1/20/03A2-22 Map Interface and Map Classes Map interface defines generic map collection methods Two implementations –HashMap: classic hash-table, not sorted –TreeMap: sorted, uses red-black trees Defines three collection views, which allow a map's contents to be viewed as one of: –set of keys; collection of values; or set of key- value mappings. Map’s order: how the iterators return their elements

1/20/03A2-23 HashMap methods Constructors: –initial capacity, optionally a load factor Object put(Object key, Object value) Object get(Object key) boolean containsKey(Object key) boolean containsValue(Object value) Object remove(Object key) Notes: key pass separately from Object Also: key must have good hashCode() defined