Introduction to Collections. 13-Nov-15

Similar documents
Class 32: The Java Collections Framework

Working with Java Collections

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Software Engineering II. Java 2 Collections. Bartosz Walter <Bartek.Walter@man.poznan.pl>

Data Structures in the Java API

Datastrukturer och standardalgoritmer i Java

JAVA COLLECTIONS FRAMEWORK

The Java Collections Framework

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

Per imparare a programmare bisogna programmare

Chapter 8: Bags and Sets

Data Structures and Algorithms

Software Development with UML and Java 2 SDJ I2, Spring 2010

Java Collections -- List Set Map

CMSC 202H. ArrayList, Multidimensional Arrays

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Practical Session 4 Java Collections

Lecture 2: Data Structures Steven Skiena. skiena

Useful Java Collections

D06 PROGRAMMING with JAVA

Principles of Software Construction: Objects, Design and Concurrency. Java Collections. toad Fall 2013

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Big O and Limits Abstract Data Types Data Structure Grand Tour.

Basic Programming and PC Skills: Basic Programming and PC Skills:

Java Coding Practices for Improved Application Performance

Java Map and Set collections

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Introduction: Abstract Data Types and Java Review

core 2 Basic Java Syntax

Data Structures and Algorithms Lists

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Object Oriented Software Design

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

CompSci-61B, Data Structures Final Exam

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

Contents. 9-1 Copyright (c) N. Afshartous

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

LINKED DATA STRUCTURES

Introduction to Object-Oriented Programming

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Java Interview Questions and Answers

Software Engineering Techniques

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Java Software Structures

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Introduction to Programming System Design. CSCI 455x (4 Units)

Java SE 8 Programming

Introduction to Stacks

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Analysis of a Search Algorithm

Collections and iterators

Lecture J - Exceptions

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

AP Computer Science Java Subset

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

4.5 Symbol Table Applications

Chapter 3: Restricted Structures Page 1

DATA STRUCTURE - STACK

CSE 143, Winter 2013 Programming Assignment #2: HTML Validator Due Thursday, July 10, 2014, 11:30 PM

AP Computer Science Java Mr. Clausen Program 9A, 9B

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Stacks. Data Structures and Data Types. Collections

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Computing Concepts with Java Essentials

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

dictionary find definition word definition book index find relevant pages term list of page numbers

cs2010: algorithms and data structures

Estrutura com iterador-1

The Interface Concept

Computer. Course Description

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Computer Science 483/580 Concurrent Programming Midterm Exam February 23, 2009

Getting Started with the Internet Communications Engine

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Programming Languages CIS 443

1 of 1 24/05/ :23 AM

Crash Course in Java

An Empirical Analysis of the Java Collections Framework Versus the C++ Standard Template Library

14/05/2013 Ed Merks EDL V1.0 1

Introduction to Java

Loops and ArrayLists

The following program is aiming to extract from a simple text file an analysis of the content such as:

Chapter 2 Introduction to Java programming

Programming Methods & Java Examples

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

CS 111 Classes I 1. Software Organization View to this point:

Transcription:

Introduction to Collections 13-Nov-15

Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections are defined in java.util The Collections framework is mostly about interfaces There are a number of predefined implementations Java 5 introduced generics and genericized all the existing collections Vectors have been redefined to implement Collection Trees, linked lists, stacks, hash tables, and other classes are implementations of Collection Arrays do not implement the Collection interfaces 2

Types of Collection Java supplies several types of Collection: Set: cannot contain duplicate elements, order is not important SortedSet: like a Set, but order is important List: may contain duplicate elements, order is important Java also supplies some collection-like things: Map: a dictionary that associates keys with values, order is not important SortedMap: like a Map, but order is important 3

The Collections hierarchy 4

Collections are ADTs Here s the good news about collections: They are elegant: they combine maximum power with maximum simplicity They are uniform: when you know how to use one, you almost know how to use them all You can easily convert from one to another And the bad news: Because there is no special syntax for them (as there is for lists, sets, and dictionaries in Python), you have to work with them using object notation 5

The Collection interface Much of the elegance of the Collections Framework arises from the intelligent use of interfaces The Collection interface specifies (among many other operations): boolean add(e o) boolean contains(object o) boolean remove(object o) boolean isempty() int size() Object[] toarray() Iterator<E> iterator() 6

Lists import java.util.*; public static void main(string args[]) { String[] array = {"Phil", "Mary", "Betty", "bob"}; List<String> mylist = Arrays.asList(array); Collections.sort(myList); System.out.println("Sorted: " + mylist); int where = Collections.binarySearch(myList, "bob"); System.out.println("bob is at " + where); Collections.shuffle(myList); System.out.println("Shuffled: " + mylist); printall(mylist); } 7

The Iterator interface An iterator is an object that will return the elements of a collection, one at a time interface Iterator<E> boolean hasnext() Returns true if the iteration has more elements E next() Returns the next element in the iteration void remove() Removes from the underlying collection the last element returned by the iterator (optional operation) 8

Using an Iterator static void printall (Collection coll) { Iterator iter = coll.iterator( ); while (iter.hasnext( )) { System.out.println(iter.next( ) ); } } hasnext() just checks if there are any more elements next() returns the next element and advances in the collection Note that this code is polymorphic it will work for any collection

New for statement The syntax of the new statement is for(type var : array) {...} or for(type var : collection) {...} Example: for(float x : myrealarray) { myrealsum += x; } For a collection class that has an Iterator, instead of for (Iterator iter = c.iterator(); iter.hasnext(); ) ((TimerTask) iter.next()).cancel(); you can now say for (TimerTask task : c) task.cancel(); Note that this for loop is implemented with an Iterator! 10

ConcurrentModificationException static void printall (Collection coll) { Iterator iter = coll.iterator( ); // When you create an iterator, a fingerprint // of the collection (list or array) is taken while (iter.hasnext( )) { System.out.println(iter.next( ) ); // Both hasnext and next check to make sure // the collection hasn t been altered, and will // throw a ConcurrentModificationException // if it has } } This means you cannot add or remove elements from the collection within the loop, or any method called from within the loop, or from some other Thread that has nothing to do with the loop 11

The Set interface A set is a collection in which: There are no duplicate elements (according to equals), and Order is not important interface Set<E> implements Collection, Iterable The methods of Set are exactly the ones in Collection The following methods are especially interesting: boolean contains(object o) // membership test boolean containsall(collection<?> c) //subset test boolean addall(collection<? extends E> c) // union boolean retainall(collection<?> c) // intersection boolean removeall(collection<?> c) // difference addall, retainall, and removeall return true if the receiving set is changed, and false otherwise 12

The List interface A list is an ordered sequence of elements interface List<E> extends Collection, Iterable Some important List methods are: void add(int index, E element) E remove(int index) boolean remove(object o) E set(int index, E element) E get(int index) int indexof(object o) int lastindexof(object o) ListIterator<E> listiterator() A ListIterator is like an Iterator, but has, in addition, hasprevious and previous methods 13

The SortedSet interface A SortedSet is a Set for which the order of elements is important interface SortedSet<E> implements Set, Collection, Iterable Two of the SortedSet methods are: E first() E last() More interestingly, only Comparable elements can be added to a SortedSet, and the set s Iterator will return these in sorted order The Comparable interface is covered in a separate lecture 14

The Map interface A map is a data structure for associating keys and values Interface Map<K,V> The two most important methods are: V put(k key, V value) // adds a key-value pair to the map V get(object key) // given a key, looks up the associated value Some other important methods are: Set<K> keyset() Returns a set view of the keys contained in this map. Collection<V> values() Returns a collection view of the values contained in this map 15

Dictionary -> HashMap hash = { one : un, two : deux, three : trois } print two ->, hash[ two ] print three ->, hash[ three ] Hashtable<String, String> table = new Hashtable<String, String>(); table.put("one", "un"); table.put("two", "deux"); table.put("three", "trois"); System.out.println("two -> " + table.get("two")); System.out.println("deux -> " + table.get("deux")); 16

The SortedMap interface A sorted map is a map that keeps the keys in sorted order Interface SortedMap<K,V> Two of the SortedMap methods are: K firstkey() K lastkey() More interestingly, only Comparable elements can be used as keys in a SortedMap, and the method Set<K> keyset() will return a set of keys whose iterator will return them sorted order The Comparable interface is covered in a separate lecture 17

Some implementations class HashSet<E> implements Set class TreeSet<E> implements SortedSet class ArrayList<E> implements List class LinkedList<E> implements List class Vector<E> implements List class Stack<E> extends Vector Important methods: push, pop, peek, isempty class HashMap<K, V> implements Map class TreeMap<K, V> implements SortedMap All of the above provide a no-argument constructor 18

The End I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships. Linus Torvalds 19