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