interfaces and collections - cas.mcmaster.cacs2s03/tutorials/t9.pdf · java collections: set of...

25

Upload: others

Post on 24-Jun-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Interfaces and CollectionsCOMPSCI 2S03

Mikhail Andrenkov

Department of Computing and Software

McMaster University

Week 9: November 14 - 18

Mikhail Andrenkov Interfaces and Collections 1 / 25

Page 2: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Outline

1 Interfaces

De�nition

Syntax

Interface Guidelines

2 Collections

Introduction

Hash Tables

ListLinkedListArrayList/VectorExample

SetHashSet

MapHashMap

3 Conceptual Exercises

Mikhail Andrenkov Interfaces and Collections 2 / 25

Page 3: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Interface De�nition

Interface: Speci�cation 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

Page 4: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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

Page 5: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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

Page 6: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Interface Guidelines

Abstract classes are used to de�ne a generalized object withinstance 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 shouldsupport the write and append methods

Generally speaking, interfaces are more �exible and improve

long-term code maintainability

Mikhail Andrenkov Interfaces and Collections 6 / 25

Page 7: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Collections Introduction

Java Collections: Set of interfaces and classes in the Javastandard library for storing �collections� of information

Collection: Grouping of information

Online Documentation

Interfaces of Interest:1 List2 Set3 Map

Mikhail Andrenkov Interfaces and Collections 7 / 25

Page 8: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Collections Hierarchy

Mikhail Andrenkov Interfaces and Collections 8 / 25

Page 9: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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

Page 10: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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 k1 and k2 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

Page 11: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Hash Table Example

One method of resolving collisions involves constructing a linked

list:

Mikhail Andrenkov Interfaces and Collections 11 / 25

Page 12: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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 LinkedList2 *ArrayList/Vector

* Your default choice

Mikhail Andrenkov Interfaces and Collections 12 / 25

Page 13: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

LinkedList Class

LinkedList: Elements possess a reference to the next elementin the sequence

�Chain� of elementsList<Type> list = new LinkedList<>();

Advantage: E�cient insert operation

Disadvantage: Slow search operation

Mikhail Andrenkov Interfaces and Collections 13 / 25

Page 14: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

ArrayList/Vector Classes

ArrayList/Vector: Elements are stored in an array; theseentries are copied to a new array when a larger (or smaller)capacity is needed

List<Type> list = new ArrayList<>();

ArrayList vs. Vector:

Extremely similarVectors are slightly slower due to synchronization overhead

Advantage: E�cient contains operation

Disadvantage: Slow insert and remove operations

Mikhail Andrenkov Interfaces and Collections 14 / 25

Page 15: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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

Page 16: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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

Page 17: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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 * HashSet2 TreeSet (Beyond the scope of this course)

* Your default choice

Mikhail Andrenkov Interfaces and Collections 17 / 25

Page 18: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

HashSet Class

HashSet: Uses a hash table to store and access elements

Set<Type> list = new HashSet<>();

Advantage: Extremely e�cient contains operation

Disadvantage: Potentially slow insert and delete operations

Mikhail Andrenkov Interfaces and Collections 18 / 25

Page 19: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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

Page 20: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Map Interface

Package: java.util.Map

Description: Represents a mapping from one set of data toanother set of data

Mapping: A function M where M : A → BTechnically not part of the Java Collections framework

Some Operations:1 containsKey

2 containsValue

3 get

4 put

Popular Implementations:1 * HashMap2 TreeMap (Beyond the scope of this course)

* Your default choice

Mikhail Andrenkov Interfaces and Collections 20 / 25

Page 21: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

HashMap Class

HashMap: Uses a hash table to associate �keys� with�values�

Map<Key_Type, Val_Type> map = new HashMap<>();

Advantage: Extremely e�cient index operation

Disadvantage: Potentially slow insert and delete operations

Mikhail Andrenkov Interfaces and Collections 21 / 25

Page 22: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

Map Example

import java.util .*;

public class Main {

public static void main(String [] args) {

Map <String , Integer > courseRatings = new HashMap <>();

courseRatings.put("BIO 1A03", 3);

courseRatings.put("MATH 1ZC3", 5);

courseRatings.put("CS 2S03", 10);

// Permutation of {BIO 1A03=3, CS 2S03=10, MATH 1ZC3 =5}

System.out.println(courseRatings);

// false

System.out.println(courseRatings.containsValue (1));

// 10

System.out.println(courseRatings.get("CS 2S03"));

courseRatings.remove("BIO 1A03");

// Permutation of {CS 2S03=10, MATH 1ZC3=5}

System.out.println(courseRatings);

}

}

Mikhail Andrenkov Interfaces and Collections 22 / 25

Page 23: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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

Page 24: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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

Page 25: Interfaces and Collections - cas.mcmaster.cacs2s03/tutorials/T9.pdf · Java Collections: Set of interfaces and classes in the Java standard library for storing collections of information

Outline Interfaces Collections Conceptual Exercises

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 integerindex in a hash table

Mikhail Andrenkov Interfaces and Collections 25 / 25