Collections, Maps and Generics

Size: px
Start display at page:

Download "Collections, Maps and Generics"

Transcription

1 Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides. Collection / \ List Set Map ArrayList HashMap Collection, List, Set and Map are all interfaces that the API provides. Remember an interface is a way to specify behaviour in Java so that we can be sure that any classes that implement the interface will have the required methods. Collection Collection is the most basic and is the root interface of the whole collection API (meaning List, Set and Map all confirm to the Collection interface). javadoc for Collection interface: A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. Collection provides for several basic methods to allow us to access and modify its contents (add, remove, isempty, size, etc). List We have already come across Lists, though you may not have known it (ArrayList implements the List interface). List differs to Collection in that it defines an order over its elements and may contain duplicates (there is a first element and a last element). Naturally List defines a couple of additional methods that aren't in Collection. The most important of which are get and set, which is result of the fact that List is an ordered collection. Set Set is a Collection that cannot contain duplicate elements. One use for a set might be the set of all anagrams of a particular word. We're not worried about order, but it is more important that we don't accidentally add multiple words to the set (which a List would allow us to do). Map Maps are used to define associations between keys and values. You can think of a Map like a dictionary, where each word is a key for its value or description. Indeed, dictionary is 1

2 one of the alternative names for a map that is sometimes used ( associative array can also be used as well). Map also defines additional methods as result of its behaviour. The most useful of which are get and put ( put is similar to set in List). Maps, like Set, are not generally ordered. Though there are some subclasses of Map that do provide an ordering (eg TreeMap). There are many, many more interfaces and classes in the Collections API that provide more functionality, but Collection, List, Set and Map are the basic interfaces. One last important point is that although you can use the concrete class of a Collection it makes more sense to use the most general interface to represent your data type when possible. That is, if I want the top 100 films on IMDB, then I'm only interested that I have a List of films. I care about which film is best so I need a List rather than a Collection, but I don't care if I use an ArrayList or LinkedList to represent that data. Example usage: 1. public List getbestfilms() { 2. List bestfilms; 3. // type is List because I care about order 4. bestfilms = new ArrayList(); 5. // implementation is an ArrayList, but I could use a 6. // LinkedList if I wanted // add films 9. return bestfilms; 10.} The main reason for this is because if you later discover that changing the type of List, Set or Map you use could increase performance then you only have to alter your code in one place. For example, only line 4 would need to change in the getbestfilms method. HashMap The HashMap is a concrete implementation of Map. It uses what is known as a hash function to map a key to a bucket where the value is stored. These buckets are usually implemented as an array. A small phone book as a HashMap source: 2

3 A hash function simply takes the contents of an object and uses it to calculate an integer value. If you wish to use one of your own classes as keys for a HashMap then it is wise to override the method hashcode (by default this is just the object's location in memory). Another requirement is that whilst your object is in use as a key it cannot have its contents changed, otherwise the Map that is using it will become invalid. For example: 1. public class Person { private final String name; 4. private final int age; // constructor // getters public int hashcode() { 12. int result = 17; 13. result = 37*result + age; 14. if (name!= null) { 15. result = 37*result + name.hashcode(); 16. } 17. return result; 18. } 19.} Why the prime numbers? (Collisions) The use of the prime numbers is to assist in reducing what is known as a collision. A collision is when two non-equal objects map to the same bucket. Usually when the hash value of the two separate keys are equal. There are two major techniques for combating collisions. The simplest is chaining. Chaining is when instead of storing just one object in a bucket, a list of objects is stored. If two objects collide then both are stored in the list. Thus, when checking for a key that has collided with another the hash table will need iterate over the list, checking each element, to determine if key points to a value in the map. The second is called open addressing. This is where if two objects collide then one is stored at the original bucket and the second is stored in the next free bucket. So when looking up if a key has a value in the hash table then the computer must first check the original bucket. If the value it represents is not there then it must check the next bucket to see if it is there and so on until it either finds the key/value pair it is looking for or it finds and empty location or in the absolute worst case goes full circle and ends up at the original bucket again. The drawback of this method is that when the hash table begins to get full its performance degrades significantly. Open addressing is the technique that HashMap uses. However, with the HashMap implementation it automatically resizes its backing array if it begins to 3

4 get too full. Generics Basic usage To use the Collections API you need to be familiar with generics. At its simplest generics is way of creating classes that do not care about the objects they are manipulating, so long as they are all of the same class. Recently you have been creating lists and trees of integers. However, if they had been made to use generics then you could have lists and trees of Strings or cars or films or even lists of lists. Creating a generic List List<String> mystrings = new ArrayList<String>(); The new syntax is the angled brackets (<>) and the bits in-between. This is known as the parameterised type. In this case it lets the compiler know that we want a List of Strings. Creating your own generic classes Let's first look at the List class we've been using in recent weeks, but made generic. 1. public class List<T> { private T head; 4. private List<T> tail; public List(T head, List<T> tail) { 7. this.head = head; 8. this.tail = tail; 9. } public T head() { 12. return head; 13. } 14.} The first part to note is the class declaration is now public class List<T> { This shows that we wish to create a generic class which will name its generic type T. We don't know what actual class we will be using, but we have to give it a pseudonym of sorts. The rest of the class reads pretty much exactly the same, except where we previously had int we now have T, and has become private List tail; 4

5 private List<T> tail; This shows that the tail of this List must also be parameterised with the same type. Bounded Types However, there is a problem with the above List class. T could be any class, and not all classes implement the functionality required for the methods we wrote. For instance, by default, Java classes do no have a natural ordering (1, 2, 3, ). Thus we must use what is know as a bounded to type to convey that the limitations that our List imposes on T. The class declaration now becomes. public class List<T extends Comparable<T>> { Here we are saying that T must implement the Comparable<T> interface. Basically we are requiring that T be comparable with itself. The sorted method would now become. 1. public static <U extends Comparable<U>> boolean sorted(list<u> list) { 2. if (list.empty() list.tail().empty()) { 3. return true; 4. } else { 5. T a = list.head(); 6. T b = list.tail().head(); 7. // generics ensures that there will always be a compareto method for a and b 8. int compareresult = a.compareto(b); 9. // 0 means they are equal 10. // <0 means a comes before b 11. // >0 means a comes after b 12. if (compareresult > 0) { 13. return false; 14. } else { 15. return sorted(list.tail()); 16. } 17. } 18. } The first thing to note is that <U extends Comparable<U>> also appears in the method signature. This line introduces a new generic type called U (only for the duration of this method). It is needed because sorted is a static method and cannot share the same generics types as instances of the class. This is because static methods can be called without reference to an object and therefore generic type. Wildcards One problem with generics is that the following is not possible (even though Cat extends Animal). 1. List<Cat> cats = new ArrayList<Cat>(); 2. List<Animal> animals = cats; This is because Dog is also an instance of Animal and if the above assignment was allowed then the following code would break the contract that the list cats only contained Cats. 5

6 animals.add(new Dog( Rex )); But what if you want to write a bit of generic code that can deal with any List of Animals and not just Cats? In generics there is the concept of a wildcard. The wildcard allows us to specify that we do not care about the actual generic type, just that it conforms to some behaviour. eg. 1. List<? extends Animal> animals1 = cats; 2. Animal someanimal = animals1.get(0); However, we cannot use add or set or any method that has a generic type as an argument for the same reasons before (we might break the contract that cats only contained Cats and not other Animals). Super keyword So far we have only been able to access the elements in a list, but what if you wanted to write generic code that added any elements to a generic list. Then the syntax becomes slightly different. Instead of writing? extends X we write? super X. This statement is saying that it is guaranteed that the wildcard is a supertype of X. 1. public static <T> void addall(list<t> src, List<? super T> dest) { 2. for (T element : src) { // for each element in src 3. dest.add(element); // add the element to dest 4. } 5. } We can now use the above method like so: 1. List<Animal> animals = new ArrayList<Animal>(); 2. List<Cat> cats = new ArrayList<Cat>(); 3. addall(cats, animals); I doubt any of you will have reason to use the super keyword in relation to generics for any of your work here. It is only included for completeness. 6

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

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other? CSM B Hashing & Heaps Spring 0 Week 0: March 0, 0 Motivation. (a) In the worst case, how long does it take to index into a linked list? Θ(N) (b) In the worst case, how long does it take to index into an

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

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

Fall 2017 Mentoring 9: October 23, Min-Heapify This. Level order, bubbling up. Level order, bubbling down. Reverse level order, bubbling up CSM B Heaps & Hashing Fall 0 Mentoring : October 3, 0 Min-Heapify This. In general, there are 4 ways to heapify. Which ways actually work? Level order, bubbling up Level order, bubbling down Reverse level

More information

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( ) Review CSE 143 Java Hashing Want to implement Sets of objects Want fast contains( ), add( ) One strategy: a sorted list OK contains( ): use binary search Slow add( ): have to maintain list in sorted order

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

MIT AITI Lecture 18 Collections - Part 1

MIT AITI Lecture 18 Collections - Part 1 MIT AITI 2004 - Lecture 18 Collections - Part 1 Collections API The package java.util is often called the "Collections API" Extremely useful classes that you must understand to be a competent Java programmer

More information

CS2110: Software Development Methods. Maps and Sets in Java

CS2110: Software Development Methods. Maps and Sets in Java CS2110: Software Development Methods Maps and Sets in Java These slides are to help with the lab, Finding Your Way with Maps This lab uses Maps, and Sets too (but just a little). Readings from textbook:

More information

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

More information

Week 16: More on Collections and Immutability

Week 16: More on Collections and Immutability Week 16: More on Collections and Immutability Jack Hargreaves jxh576@cs.bham.ac.uk Febuary 9, 2012 1 Collections API Last week we looked at Collection, List, Set and Map the basic data type interfaces

More information

1.00 Lecture 32. Hashing. Reading for next time: Big Java Motivation

1.00 Lecture 32. Hashing. Reading for next time: Big Java Motivation 1.00 Lecture 32 Hashing Reading for next time: Big Java 18.1-18.3 Motivation Can we search in better than O( lg n ) time, which is what a binary search tree provides? For example, the operation of a computer

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

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

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

More information

Review: Trees Binary Search Trees Sets in Java Collections API CS1102S: Data Structures and Algorithms 05 A: Trees II

Review: Trees Binary Search Trees Sets in Java Collections API CS1102S: Data Structures and Algorithms 05 A: Trees II 05 A: Trees II CS1102S: Data Structures and Algorithms Martin Henz February 10, 2010 Generated on Wednesday 10 th February, 2010, 10:54 CS1102S: Data Structures and Algorithms 05 A: Trees II 1 1 Review:

More information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Introducing Hashing. Chapter 21. Copyright 2012 by Pearson Education, Inc. All rights reserved

Introducing Hashing. Chapter 21. Copyright 2012 by Pearson Education, Inc. All rights reserved Introducing Hashing Chapter 21 Contents What Is Hashing? Hash Functions Computing Hash Codes Compressing a Hash Code into an Index for the Hash Table A demo of hashing (after) ARRAY insert hash index =

More information

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

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

University of Maryland College Park Dept of Computer Science

University of Maryland College Park Dept of Computer Science University of Maryland College Park Dept of Computer Science CMSC132H Fall 2009 Midterm First Name (PRINT): Last Name (PRINT): University ID: I pledge on my honor that I have not given or received any

More information

Interfaces and Collections

Interfaces and Collections 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

More information

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

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani The Collection Framework Collection: an aggregate that can hold a varying number of elements Interface:

More information

1B1b Implementing Data Structures Lists, Hash Tables and Trees

1B1b Implementing Data Structures Lists, Hash Tables and Trees 1B1b Implementing Data Structures Lists, Hash Tables and Trees Agenda Classes and abstract data types. Containers. Iteration. Lists Hash Tables Trees Note here we only deal with the implementation of data

More information

CS11 Java. Winter Lecture 8

CS11 Java. Winter Lecture 8 CS11 Java Winter 2010-2011 Lecture 8 Java Collections Very powerful set of classes for managing collections of objects Introduced in Java 1.2 Provides: Interfaces specifying different kinds of collections

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Slide 1 CS 170 Java Programming 1

Slide 1 CS 170 Java Programming 1 CS 170 Java Programming 1 Objects and Methods Performing Actions and Using Object Methods Slide 1 CS 170 Java Programming 1 Objects and Methods Duration: 00:01:14 Hi Folks. This is the CS 170, Java Programming

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

COMP 250. inheritance (cont.) interfaces abstract classes

COMP 250. inheritance (cont.) interfaces abstract classes COMP 250 Lecture 31 inheritance (cont.) interfaces abstract classes Nov. 20, 2017 1 https//goo.gl/forms/ymqdaeilt7vxpnzs2 2 class Object boolean equals( Object ) int hashcode( ) String tostring( ) Object

More information

CS2110: Software Development Methods. Maps and Sets in Java

CS2110: Software Development Methods. Maps and Sets in Java CS2110: Software Development Methods Maps and Sets in Java These slides are to help with the lab, Finding Your Way with Maps Today s lab uses Maps (and Sets but just a little). Readings from textbook:

More information

PIC 20A Collections and Data Structures

PIC 20A Collections and Data Structures PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

Exercise 8 Parametric polymorphism November 18, 2016

Exercise 8 Parametric polymorphism November 18, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 8 Parametric polymorphism November 18, 2016 Task 1 Consider the following Scala classes: class A class B extends A class P1[+T] class P2[T

More information

Computer Science II (Spring )

Computer Science II (Spring ) Computer Science II 4003-232-01 (Spring 2007-2008) Week 5: Generics, Java Collection Framework Richard Zanibbi Rochester Institute of Technology Generic Types in Java (Ch. 21 in Liang) What are Generic

More information

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation CSE 331 Software Design and Implementation Lecture 15 Generics 2 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

CSE 331 Software Design and Implementation. Lecture 15 Generics 2 CSE 331 Software Design and Implementation Lecture 15 Generics 2 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

Inheritance (Part 2) Notes Chapter 6

Inheritance (Part 2) Notes Chapter 6 Inheritance (Part 2) Notes Chapter 6 1 Object Dog extends Object Dog PureBreed extends Dog PureBreed Mix BloodHound Komondor... Komondor extends PureBreed 2 Implementing Inheritance suppose you want to

More information

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

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel) Programmieren II Polymorphism Alexander Fraser fraser@cl.uni-heidelberg.de (Based on material from T. Bögel) June 4, 2014 1 / 50 Outline 1 Recap - Collections 2 Advanced OOP: Polymorphism Polymorphism

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 James Wilcox / Winter 2016 Hi, I m James! Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping

More information

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

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering Readings and References Java Collections "Collections", Java tutorial http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Spring 2004 Software Engineering http://www.cs.washington.edu/education/courses/403/04sp/

More information

COMP 250. Lecture 29. interfaces. Nov. 18, 2016

COMP 250. Lecture 29. interfaces. Nov. 18, 2016 COMP 250 Lecture 29 interfaces Nov. 18, 2016 1 ADT (abstract data type) ADT s specify a set of operations, and allow us to ignore implementation details. Examples: list stack queue binary search tree priority

More information

Garbage Collection (1)

Garbage Collection (1) Coming up: Today: Finish unit 6 (garbage collection) start ArrayList and other library objects Wednesday: Complete ArrayList, basics of error handling Friday complete error handling Next week: Recursion

More information

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

Tutorial #11 SFWR ENG / COMP SCI 2S03. Interfaces and Java Collections. Week of November 17, 2014 Tutorial #11 SFWR ENG / COMP SCI 2S03 Interfaces and Java Collections Week of November 17, 2014 Interfaces An interface defines a specification or contract that a class must meet to be defined as an instance

More information

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism Lecture Outline Parametric Polymorphism and Java Generics Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards

More information

Questions. 6. Suppose we were to define a hash code on strings s by:

Questions. 6. Suppose we were to define a hash code on strings s by: Questions 1. Suppose you are given a list of n elements. A brute force method to find duplicates could use two (nested) loops. The outer loop iterates over position i the list, and the inner loop iterates

More information

CSE373 Fall 2013, Second Midterm Examination November 15, 2013

CSE373 Fall 2013, Second Midterm Examination November 15, 2013 CSE373 Fall 2013, Second Midterm Examination November 15, 2013 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, closed calculator, closed electronics. Please

More information

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

27/04/2012. Objectives. Collection. Collections Framework. Collection Interface. Collection algorithm. Legacy collection Objectives Collection Collections Framework Concrete collections Collection algorithm By Võ Văn Hải Faculty of Information Technologies Summer 2012 Legacy collection 1 2 2/27 Collections Framework "Collection"

More information

Points off Total off Net Score. CS 314 Final Exam Spring 2017

Points off Total off Net Score. CS 314 Final Exam Spring 2017 Points off 1 2 3 4 5 6 Total off Net Score CS 314 Final Exam Spring 2017 Your Name Your UTEID Instructions: 1. There are 6 questions on this test. 100 points available. Scores will be scaled to 300 points.

More information

Topic 10: The Java Collections Framework (and Iterators)

Topic 10: The Java Collections Framework (and Iterators) Topic 10: The Java Collections Framework (and Iterators) A set of interfaces and classes to help manage collections of data. Why study the Collections Framework? very useful in many different kinds of

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 Zach Tatlock / Spring 2018 Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping Using wildcards

More information

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

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework Announcements Abstract data types (again) PS 5 ready Tutoring schedule updated with more hours Today s topic: The Java Collections Framework Reading: Section 7.5 An ADT is a model of a collection of data

More information

Collections (Java) Collections Framework

Collections (Java) Collections Framework Collections (Java) https://docs.oracle.com/javase/tutorial/collections/index.html Collection an object that groups multiple elements into a single unit. o store o retrieve o manipulate o communicate o

More information

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students.  Collections. Play with problem set 1 Today Book-keeping Exceptions Subscribe to sipb-iap-java-students Collections http://sipb.mit.edu/iap/java/ Play with problem set 1 No class Monday (MLK); happy Hunting Problem set 2 on Tuesday 1 2 So

More information

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam 1.00/1.001 Introduction to Computers and Engineering Problem Solving Final Exam Name: Email Address: TA: Section: You have three hours to complete this exam. For coding questions, you do not need to include

More information

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. Inf1-OP Inheritance UML Class Diagrams UML: language for specifying and visualizing OOP software systems UML class diagram: specifies class name, instance variables, methods,... Volker Seeker, adapting

More information

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017 COMP 250 Lecture 32 interfaces (Comparable, Iterable & Iterator) Nov. 22/23, 2017 1 Java Comparable interface Suppose you want to define an ordering on objects of some class. Sorted lists, binary search

More information

CS 310: Hash Table Collision Resolution

CS 310: Hash Table Collision Resolution CS 310: Hash Table Collision Resolution Chris Kauffman Week 8-1 Logistics Reading Weiss Ch 20: Hash Table Weiss Ch 6.7-8: Maps/Sets Homework HW 1 Due Saturday Discuss HW 2 next week Questions? Schedule

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Interface Abstract data types Version of January 26, 2013 Abstract These lecture notes are meant

More information

Generalized Code. Fall 2011 (Honors) 2

Generalized Code. Fall 2011 (Honors) 2 CMSC 202H Generics Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using base classes is general, but restricted to a single class hierarchy

More information

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional)

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional) COMP-202 Unit 7: More Advanced OOP CONTENTS: ArrayList HashSet (Optional) HashMap (Optional) Managing a big project Many times, you will need to use an Object type that someone else has created. For example,

More information

Java Map and Set collections

Java Map and Set collections Java Map and Set collections Java Set container idea interface Java Map container idea interface iterator concordance example Java maps and sets [Bono] 1 Announcements This week s lab based on an example

More information

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics Inf1-OP Inheritance Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 12, 2018 UML Class Diagrams UML: language for specifying and visualizing OOP software

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Dynamic Data Structures and Generics

Dynamic Data Structures and Generics Dynamic Data Structures and Generics Reading: Savitch ch. 12 Objectives Introduce Abstract Data Types (ADTs) and review interfaces Introduce Java's ArrayList class Learn about linked lists and inner classes

More information

CMSC 202. Containers

CMSC 202. Containers CMSC 202 Containers Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects. Arrays are compiler-supported containers.

More information

Standard ADTs. Lecture 19 CS2110 Summer 2009

Standard ADTs. Lecture 19 CS2110 Summer 2009 Standard ADTs Lecture 19 CS2110 Summer 2009 Past Java Collections Framework How to use a few interfaces and implementations of abstract data types: Collection List Set Iterator Comparable Comparator 2

More information

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types generics enable types (classes and interfaces) to be parameters when defining

More information

University of Maryland College Park Dept of Computer Science

University of Maryland College Park Dept of Computer Science University of Maryland College Park Dept of Computer Science CMSC132H Fall 2009 Midterm Key Problem 1 (12 pts) Algorithmic Complexity 1. (6 pts) Calculate the asymptotic complexity of the code snippets

More information

Parametric polymorphism and Generics

Parametric polymorphism and Generics Parametric polymorphism and Generics Today s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping.

More information

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

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps Today's Agenda > To give a practical introduction to data structures > To look specifically at Lists, Sets, and Maps > To talk briefly about Generics in Java > To talk about interfaces in Java Data Structures

More information

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

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion Prelim 1 CS 2110, October 1, 2015, 5:30 PM 0 1 2 3 4 5 Total Question Name True Short Testing Strings Recursion False Answer Max 1 20 36 16 15 12 100 Score Grader The exam is closed book and closed notes.

More information

CSE 331 Final Exam 3/12/12

CSE 331 Final Exam 3/12/12 Name There are 12 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes, closed

More information

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I Hashing Reading: L&C 17.1, 17.3 Eck 10.3 Defne hashing Objectives Discuss the problem of collisions in hash tables Examine Java's HashMap implementation of hashing Look at HashMap example Save serializable

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming

More information

USAL1J: Java Collections. S. Rosmorduc

USAL1J: Java Collections. S. Rosmorduc USAL1J: Java Collections S. Rosmorduc 1 A simple collection: ArrayList A list, implemented as an Array ArrayList l= new ArrayList() l.add(x): adds x at the end of the list l.add(i,x):

More information

Midterm Exam 2 CS 455, Spring 2011

Midterm Exam 2 CS 455, Spring 2011 Name: USC loginid (e.g., ttrojan): Midterm Exam 2 CS 455, Spring 2011 March 31, 2011 There are 6 problems on the exam, with 50 points total available. There are 7 pages to the exam, including this one;

More information

Java Collection Framework

Java Collection Framework Java Collection Framework Readings Purpose To provide a working knowledge of the Java Collections framework and iterators. Learning Objectives Understand the structure of the Java Collections framework

More information

MIDTERM EXAM THURSDAY MARCH

MIDTERM EXAM THURSDAY MARCH Week 6 Assignments: Program 2: is being graded Program 3: available soon and due before 10pm on Thursday 3/14 Homework 5: available soon and due before 10pm on Monday 3/4 X-Team Exercise #2: due before

More information

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

Points off Total off Net Score. CS 314 Final Exam Spring Your Name Your UTEID Points off 1 2 3 4 5 6 Total off Net Score CS 314 Final Exam Spring 2018 Your Name Your UTEID Instructions: 1. There are 6 questions on this test. 100 points available. Scores will be scaled to 300 points.

More information

Assignment 4: Hashtables

Assignment 4: Hashtables Assignment 4: Hashtables In this assignment we'll be revisiting the rhyming dictionary from assignment 2. But this time we'll be loading it into a hashtable and using the hashtable ADT to implement a bad

More information

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

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1 COMP209 Object Oriented Programming Container Classes 3 Mark Hall List Functionality Types List Iterator Adapter design pattern Adapting a LinkedList to a Stack/Queue Map Functionality Hashing Performance

More information

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock) Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map Lecture 15 Summary Collections Framework Iterable, Collections List, Set Map Collections class Comparable and Comparator 1 By the end of this lecture, you will be able to use different types of Collections

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering Readings and References Java Collections References» "Collections", Java tutorial» http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Winter 2003 Software Engineering http://www.cs.washington.edu/education/courses/403/03wi/

More information

Practical Session 3 Java Collections

Practical Session 3 Java Collections Practical Session 3 Java Collections 1 Outline Working with a Collection The Collection interface The Collection hierarchy Case Study: Undoable Stack Maps The Collections class Wrapper classes 2 Collection

More information

Csci 102: Sample Exam

Csci 102: Sample Exam Csci 102: Sample Exam Duration: 65 minutes Name: NetID: Student to your left: Student to your right: DO NOT OPEN THIS EXAM UNTIL INSTRUCTED Instructions: Write your full name and your NetID on the front

More information

Unit5: Packages and abstraction

Unit5: Packages and abstraction Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 1. Introduction The java.util package 2 M257_Unit_5 1 1. Introduction This unit discusses the following: (1) Packages: Java Packages: The Java language provides

More information

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011 MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011 1 Goals of the Lecture Continue a review of fundamental object-oriented concepts 2 Overview of OO Fundamentals

More information

Outline. iterator review iterator implementation the Java foreach statement testing

Outline. iterator review iterator implementation the Java foreach statement testing Outline iterator review iterator implementation the Java foreach statement testing review: Iterator methods a Java iterator only provides two or three operations: E next(), which returns the next element,

More information

STANDARD ADTS Lecture 17 CS2110 Spring 2013

STANDARD ADTS Lecture 17 CS2110 Spring 2013 STANDARD ADTS Lecture 17 CS2110 Spring 2013 Abstract Data Types (ADTs) 2 A method for achieving abstraction for data structures and algorithms ADT = model + operations In Java, an interface corresponds

More information

Collections Algorithms

Collections Algorithms Collections Algorithms 1 / 11 The Collections Framework A collection is an object that represents a group of objects. The collections framework allows different kinds of collections to be dealt with in

More information

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8 Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

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

NAME: c. (true or false) The median is always stored at the root of a binary search tree. EE 322C Spring 2009 (Chase) Exam 2: READ THIS FIRST. Please use the back side of each page for scratch paper. For some of the questions you may need to think quite a bit before you write down an answer.

More information

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method

More information

Collections Questions

Collections Questions Collections Questions https://www.journaldev.com/1330/java-collections-interview-questions-and-answers https://www.baeldung.com/java-collections-interview-questions https://www.javatpoint.com/java-collections-interview-questions

More information

CS61BL Summer 2013 Midterm 2

CS61BL Summer 2013 Midterm 2 CS61BL Summer 2013 Midterm 2 Sample Solutions + Common Mistakes Question 0: Each of the following cost you.5 on this problem: you earned some credit on a problem and did not put your five digit on the

More information

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6 Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6 Prepared for course 160410/411 Michael C. Kunkel m.kunkel@fz-juelich.de Materials taken from; docs.oracle.com Teach Yourself

More information