Interfaces and Collections

Similar documents
Tutorial #11 SFWR ENG / COMP SCI 2S03. Interfaces and Java Collections. Week of November 17, 2014

Collections, Maps and Generics

Building Java Programs

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Collections Questions

Distributed Systems Recitation 1. Tamim Jabban

Java Collections Framework reloaded

Collections. James Brucker

CS2110: Software Development Methods. Maps and Sets in Java

CS2110: Software Development Methods. Maps and Sets in Java

13 A: External Algorithms II; Disjoint Sets; Java API Support

Building Java Programs

Interfaces, collections and comparisons

MIDTERM EXAM THURSDAY MARCH

CS 310: Maps and Sets and Trees

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

Computer Science II (Spring )

PVS. Empirical Study of Usage and Performance of Java Collections. Diego Costa, 1 Artur Andrzejak, 1 Janos Seboek, 2 David Lo

CS 310: Maps and Sets

Computer Science II (20082) Week 1: Review and Inheritance

CMPT 126: Lecture 11 Collections: Abstract Data Types and Dynamic Representation (Chapt. 12)

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods

PIC 20A Collections and Data Structures

Fall 2017 Mentoring 9: October 23, Min-Heapify This. Level order, bubbling up. Level order, bubbling down. Reverse level order, bubbling up

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

Distributed Systems Recitation 1. Tamim Jabban

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

Computer Science II (20073) Week 1: Review and Inheritance

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Linked Lists. References and objects

Java Collections Framework

Hash tables. hashing -- idea collision resolution. hash function Java hashcode() for HashMap and HashSet big-o time bounds applications

Advanced Programming Generics Collections

ArrayList. Introduction. java.util.arraylist

TECHNICAL WHITEPAPER. Performance Evaluation Java Collections Framework. Performance Evaluation Java Collections. Technical Whitepaper.

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Midterm Exam 2 CS 455, Spring 2011

CONTAİNERS COLLECTİONS

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

5/23/2015. Core Java Syllabus. VikRam ShaRma

CS 307 Final Spring 2010

CIT-590 Final Exam. Name: Penn Key (Not ID number): If you write a number above, you will lose 1 point

type conversion polymorphism (intro only) Class class

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Java Collections Framework. 24 April 2013 OSU CSE 1

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

Midterm Exam CS 251, Intermediate Programming March 6, 2015

Building Java Programs

Parametric polymorphism and Generics

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

Examination Questions Midterm 1

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Set<Integer> s = new TreeSet<Integer>(); s.add( 7 ); s.add( 7 ); System.out.println( s.size() );

CS 314 Final Fall 2012

CS11 Java. Winter Lecture 8

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

CMSC 202. Containers

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

First IS-A Relationship: Inheritance

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

Collections (Java) Collections Framework

What is the Java Collections Framework?

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Hash table basics mod 83 ate. ate

COMP 250. Lecture 27. hashing. Nov. 10, 2017

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016

Lab5. Wooseok Kim

11/27/12. CS202 Fall 2012 Lecture 11/15. Hashing. What: WiCS CS Courses: Inside Scoop When: Monday, Nov 19th from 5-7pm Where: SEO 1000

Practical Session 3 Java Collections

MIT AITI Lecture 18 Collections - Part 1

Computational Expression

CS 455 Final Exam Fall 2012 [Bono] Dec. 17, 2012

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

An Interface with Generics

Building Java Programs

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Regular Expressions ("reguläre Ausdrücke", "regexp")

Points off Total off Net Score. CS 314 Final Exam Spring Your Name Your UTEID

Practice exam for CMSC131-04, Fall 2017

Crash Course Review Only. Please use online Jasmit Singh 2

Software Development (cs2500)

Get started with the Java Collections Framework By Dan Becker

Exploring the Java API, Packages & Collections

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

Midterm Exam 2 CS 455, Spring 2015

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018

JAVA COLLECTION FRAMEWORK & SETS

Transcription:

Interfaces and Collections COMPSCI 2S03 Mikhail Andrenkov Department of Computing and Software McMaster University Week 9: November 14-18 Mikhail Andrenkov Interfaces and Collections 1 / 25

Outline 1 Interfaces Denition Syntax Interface Guidelines 2 Collections Introduction Hash Tables List LinkedList ArrayList/Vector Example Set HashSet Map HashMap 3 Conceptual Exercises Mikhail Andrenkov Interfaces and Collections 2 / 25

Interface Denition Interface: Specication or contract that all implementing classes must satisfy Interfaces are not classes; they cannot be instantiated All methods in an interface must be implemented by the implementing class Classes can implement any number of interfaces However, classes can only extend one other class Mikhail Andrenkov Interfaces and Collections 3 / 25

Interface Declaration Syntax public interface InterfaceName { // Constants public static final int INT_VAR = 0; public static final boolean BOOL_VAR = true ;... // Methods public void methodone () ; public int methodtwo ( String argument );... Dog Example: public interface Dog { public void eat ( String food ); public String bark () ; public String getname () ; Mikhail Andrenkov Interfaces and Collections 4 / 25

Interface Implementation Syntax public class ClassName implements InterfaceName { // Interface Methods public void methodone () {... public int methodtwo ( String argument ) {...... Dog Example: public class Chihuahua implements Dog { public void eat ( String food ) { System. out. println (" Yum!"); public String bark () { return " Bark!"; public String getname () { return this. name ;... Mikhail Andrenkov Interfaces and Collections 5 / 25

Interface Guidelines Abstract classes are used to dene a generalized object with instance variables and methods Example: Dog and Polygon should be abstract classes Interfaces are used to describe a capability of a class Example: Classes implementing the Writer interface should support the write and append methods Generally speaking, interfaces are more exible and improve long-term code maintainability Mikhail Andrenkov Interfaces and Collections 6 / 25

Collections Introduction Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information Collection: Grouping of information Online Documentation Interfaces of Interest: 1 List 2 Set 3 Map Mikhail Andrenkov Interfaces and Collections 7 / 25

Collections Hierarchy Mikhail Andrenkov Interfaces and Collections 8 / 25

Collections Conversion All Collections classes can be trivially converted between one another The Collections interface requires the implementation of an addall(collection<e> c) method Example: List < Integer > list = new LinkedList < >() ; for ( int i = 0 ; i < 5 ; i ++) list. add (i); Set < Integer > set = new HashSet < >() ; set. addall ( list ); // Contains {0, 1, 2, 3, 4 Mikhail Andrenkov Interfaces and Collections 9 / 25

Hash Tables Hash Table: Data structure that uses a hash function H : K Z to map a set K of keys to a set of V of values through an index When a hash function is applied to a key, an index in the hash table is returned This index can be used to nd the value associated with the key Collision: Event where two distinct keys k 1 and k 2 generate the same hash code Collisions should be avoided wherever possible The hash code for an instance of a Java class C is generated by calling C 's int hashcode() method Mikhail Andrenkov Interfaces and Collections 10 / 25

Hash Table Example One method of resolving collisions involves constructing a linked list: Mikhail Andrenkov Interfaces and Collections 11 / 25

List Interface Package: java.util.list Description: Represents a list of ordered data Some Operations: 1 add 2 contains 3 get 4 indexof 5 remove Popular Implementations: 1 LinkedList 2 *ArrayList/Vector * Your default choice Mikhail Andrenkov Interfaces and Collections 12 / 25

LinkedList Class LinkedList: Elements possess a reference to the next element in the sequence Chain of elements List<Type> list = new LinkedList<>(); Advantage: Ecient insert operation Disadvantage: Slow search operation Mikhail Andrenkov Interfaces and Collections 13 / 25

ArrayList/Vector Classes ArrayList/Vector: Elements are stored in an array; these entries are copied to a new array when a larger (or smaller) capacity is needed List<Type> list = new ArrayList<>(); ArrayList vs. Vector: Extremely similar Vectors are slightly slower due to synchronization overhead Advantage: Ecient contains operation Disadvantage: Slow insert and remove operations Mikhail Andrenkov Interfaces and Collections 14 / 25

ArrayList/Vector Demonstration ArrayList<Integer> list = new ArrayList<>(); for (int i = 0 ; i < 3; i++) list.add(i); list.add(3); list.add(4); Mikhail Andrenkov Interfaces and Collections 15 / 25

List Example import java. util.*; public class Main { public static void main ( String [] args ) { List < String > fruit = new LinkedList < >() ; fruit. add (" Apple "); fruit. add (" Banana "); fruit. add (" Citrus "); // [ Apple, Banana, Citrus ] System. out. println ( fruit ); // Apple System. out. println ( fruit. get (0) ); fruit. remove (1) ; // [ Apple, Citrus ] System. out. println ( fruit ); Mikhail Andrenkov Interfaces and Collections 16 / 25

Set Interface Package: java.util.set Description: Represents a set of data Set: Unordered group of unique elements Some Operations: 1 add 2 contains 3 isempty 4 remove Popular Implementations: 1 * HashSet 2 TreeSet (Beyond the scope of this course) * Your default choice Mikhail Andrenkov Interfaces and Collections 17 / 25

HashSet Class HashSet: Uses a hash table to store and access elements Set<Type> list = new HashSet<>(); Advantage: Extremely ecient contains operation Disadvantage: Potentially slow insert and delete operations Mikhail Andrenkov Interfaces and Collections 18 / 25

Set Example import java. util.*; public class Main { public static void main ( String [] args ) { Set < String > countries = new HashSet < >() ; countries. add (" Argentina "); countries. add (" Brazil "); countries. add (" Canada "); countries. add (" Canada "); // Permutation of [ Argentina, Brazil, Canada ] System. out. println ( countries ); // true System. out. println ( countries. contains (" Brazil ")); countries. remove (" Canada "); // Permutation of [ Argentina, Brazil ] System. out. println ( countries ); Mikhail Andrenkov Interfaces and Collections 19 / 25

Map Interface Package: java.util.map Description: Represents a mapping from one set of data to another set of data Mapping: A function M where M : A B Technically not part of the Java Collections framework Some Operations: 1 containskey 2 containsvalue 3 get 4 put Popular Implementations: 1 * HashMap 2 TreeMap (Beyond the scope of this course) * Your default choice Mikhail Andrenkov Interfaces and Collections 20 / 25

HashMap Class HashMap: Uses a hash table to associate keys with values Map<Key_Type, Val_Type> map = new HashMap<>(); Advantage: Extremely ecient index operation Disadvantage: Potentially slow insert and delete operations Mikhail Andrenkov Interfaces and Collections 21 / 25

Map Example import java. util.*; public class Main { public static void main ( String [] args ) { Map < String, Integer > courseratings = new HashMap < >() ; courseratings. put (" BIO 1 A03 ", 3) ; courseratings. put (" MATH 1 ZC3 ", 5) ; courseratings. put (" CS 2 S03 ", 10) ; // Permutation of { BIO 1 A03 =3, CS 2 S03 =10, MATH 1 ZC3 =5 System. out. println ( courseratings ); // false System. out. println ( courseratings. containsvalue (1) ); // 10 System. out. println ( courseratings. get (" CS 2 S03 ")); courseratings. remove (" BIO 1 A03 "); // Permutation of { CS 2 S03 =10, MATH 1 ZC3 =5 System. out. println ( courseratings ); Mikhail Andrenkov Interfaces and Collections 22 / 25

Exercises - Interface Design Select the superior interface design: A: public int addallelements ( LinkedList < Integer > list ) { int total = 0; for ( Integer element : list ) total += element ; return total ; B: public int addallelements ( List < Integer > list ) { int total = 0; for ( Integer element : list ) total += element ; return total ; Mikhail Andrenkov Interfaces and Collections 23 / 25

Exercises - Data Structure Selection For each of the following scenarios, identify the most appropriate Collections interface to use: 1 A satellite in space wishes to collect a large quantity of radiation samples and then determine its maximum radiation dosage. 2 A school database needs to quickly locate a grade given the student's rst and last name. 3 A data analyst would like to store all sentences containing a % from an array of String sentences. Mikhail Andrenkov Interfaces and Collections 24 / 25

Exercises - Advanced Questions Answer the following questions and justify your conclusions: 1 It is possible to implement List and Set behaviour using a Map. Why is Map excluded from the Java Collections framework? 2 Although interfaces do not contain any implementation, are they still useful to the Java compiler? 3 What are some characteristics of a desirable hash function? Recall that hash functions map input elements to an integer index in a hash table Mikhail Andrenkov Interfaces and Collections 25 / 25