What is the Java Collections Framework?

Size: px
Start display at page:

Download "What is the Java Collections Framework?"

Transcription

1 1 of 13

2 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several more. I hold my collection of s in an folder on my computer. In the context of object oriented programming, a collection is an object that groups multiple objects into a single collection. It is used to store, retrieve, manipulate and transmit a collection of data from one method to another. In Java, the Collections Framework is an architecture that can be used for representing and manipulating collections. All collections frameworks involve three things: 1. Interfaces 2. Implementations 3. Algorithms Interfaces are ADT (abstract data types) used to represent collections. Interfaces are typically used to manipulate collections without being bound to a particular implementation. Implementations are Java programs that are written based on the interfaces to provide the functionality, in this case, that of the collections. Typically these implementations can be reused. Algorithms are the specific set of steps of the Java program used in implementation. Some examples are the searching and sorting algorithms used in implementing the collections interface. The benefits of using a Collections Framework are 1. It offers rich and reusable data structures and algorithms so useful in problem solving 2. The data structures and algorithms are usually high-quality and high-performance ones 3. Various implementations of the interfaces are interchangeable 4. Offers interoperability between unrelated APIs Interfaces Collection interfaces enable a degree of control over the collections and facilitate passing collections to myriad of methods. In other words, interfaces enable manipulation of collections independent of implementation. In Java, the Collection interfaces are Set o List Sorted Set We also have the Map interfaces, but it is not really treated as a part of the Collections interface hierarchy. It has 2 of 13

3 Map o Sorted Map It is important to know that the JDK does not provide separate interfaces for each variant of each collection type. Some salient features are 1. It enables managing the number of core collection interfaces easily 2. The only variants possible are a. Immutable b. fixed-size c. append-only 3. The modification operations in each of the interfaces are optional. This is also done to cope with these variants. 4. It is possible that certain implementations may not support some of these operations. If an unsupported operation is invoked, the collection throws an exception. This exception is called the UnsupportedOperationException. 5. It is the responsibility of the different implementations to provide the details of the operations that are supported, in the documentation of the implementation. 6. The JDK's general-purpose implementations support all the optional operations. Links to Good Tutorials on Collection Framework 1. An exhaustive tutorial from NTU, Singapore at 2. There are a series of video tutorials from the Cave of Programming. The Part 1 of the Java Collection framework is at Learning to Use the Collection Interface The Collection interface can be depicted as a hierarchy. the Collection interface is at the root of the collection hierarchy. Elements are the group of objects that a collection represents. Duplicates: In some collection implementations duplicate elements are allowed, while in others it is not allowed. Ordering: Some implementations of the Collection interface are ordered, while others are not. Implementations: The implementations of the Collection interfaces do not come directly from the JDK. The JDK provides the implementations of its sub-interfaces. The Collection interface is used to pass collections between methods and manipulate them when maximum generality is required. Example: Collection implementations usually have a constructor with a Collection as one of the parameters. This constructor is used to initialize the new Collection to contain all the 3 of 13

4 elements in the specified Collection. By invoking this constructor, we are able to create a Collection of a desired implementation type, initially containing all the elements in any given Collection. This regardless of whatever is its sub-interface or implementation type. Thus, if we have a collection mycollection, which is a List or a set or any other type of Collection; we can create a new ArrayList having all the elements in mycollection. A way of achieving this is shown below. List mylist = new ArrayList(myCollection); // Given below is the Collection interface public interface Collection { // These are the Basic Operations int size(); boolean isempty(); boolean contains(object element); boolean add(object element); //Optional boolean remove(object element); // Optional Iterator iterator(); // Bulk Operations boolean containsall(collection mycollection); boolean addall(collection mycollection); // Optional boolean removeall(collection mycollection); // Optional boolean retainall(collection mycollection); // Optional void clear(); // Optional // These are Array Operations Object[] toarray(); Object[] toarray(object a[]); The Collection interface has the following methods. 1. To add elements to a collection. The add() method is implemented such that it can allow duplicate elements to be present or it does not allow the duplicate elements to be present. The method returns true if the collection has changed fooling the execution of this method. 2. To remove elements from a collection. The remove() method enables one to remove a single instance of the element from the collection. This method returns true if the collection has changed after execution of the method. 3. To iterate over elements of a collection. The object returned by the iterator() method is similar to an enumeration. But differs in two ways. a. When we call the iterator() method, it allows us to remove an element from the collection during iteration. b. When we are moving through an enumeration, we cannot remove an element from the collection without compromising safety. 4 of 13

5 The Iterator interface is displayed below. public interface Iterator{ boolean hasnext(); Object next(); // Optional ones void remove(); 4. To check if a next element is present. The hasnext() method is similar to the Enumeration.hasMoreElements() method, while the next() method is similar to the Enumeration.nextElement() method. The remove() method removes the last element returned by the next() method from the collection. The remove() method can be called only once for every call to the next() method. An exception is thrown if a violation occurs. Example: Traversing a collection and removing elements. Suppose we want to traverse a collection and simultaneously remove such elements that do not satisfy a specific condition. We can use the iterator to perform this task. static void removeelementthatfailscondition(collection mycollection) { for (Iterator k = mycollection.iterator(); k.hasnext(); ) if (conditionfails(k.next())) k.remove(); Let us spend a minute and examine this segment of code. This method would work regardless of what the collection contains and regardless of the collection implementation. Essentially, this method is polymorphic. Bulk Operations on Collections Bulk operations can be used to manipulate the contents of an entire collection at a time. 1. containsall: 2. addall: a. This returns true if the target collection contains all the elements in the specified collection. a. This adds all the elements of the specified collection to the target collection. 5 of 13

6 b. The method returns return true if the target collection was modified on executing the method. 3. removeall: a. This removes from the target collection all those elements that are also present in the specified collection. b. The method returns return true if the target collection was modified on executing the method. 4. retainall: 5. clear: a. This removes from the target collection all its elements that are not also present in the specified collection. b. In other words, it retains only those elements in the target collection that are also present in the specified collection. c. The method returns return true if the target collection was modified on executing the method. a. It removes all elements from the collection. Example: To remove all instances of a specified element myelement from the collection mycollection. mycollection.removeall(collections.singleton(myelement)); Example: To remove all null elements from the collection mycollection. mycollection.removeall(collections.singleton(null)); Do note the use of the Collections.singleton(). This is a factory method. This returns a Set that is immutable, and containing the specified element{s). Array Methods These are available to act as bridge between the collections and cases where APIs expect arrays as input. 6 of 13

7 1. The toarray() method without any arguments creates a new array of objects. 2. The toarray() method can also take parameters to provide an array or to choose the runtime type of the output array. Example: To place the contents of the collection mycollection onto a newly created array of objects whose length is equal to the number of elements in mycollection. Object[] myobject = mycollection.toarray(); Example: To place the contents of mycollection into a newly created array of String type whose length is equal to the number of elements in mycollection. String[] mystrings = (String[]) mycollection.toarray(new String[0]); These are just simple examples. One needs to solve many problems, often of a non-trivial variety to gain good competencies in using the Collections. Learning to Use the Set Interface We have encountered the mathematical abstraction called set. In Java, a set is a special type of collection. It does not contain duplicate elements, just like its mathematical counterpart. The Set interface is a subset of the Collection interface and contains only those methods that are inherited from the Collection interface. It does not contain any other additional method. A set allows for versatile behavior of the equals and hashcode operations. The power of equals and hashcode allow set objects with different implementations to be compared meaningfully. Remember that two Set objects containing the same objects are considered equal. In Java, the Set interface is as displayed below. 7 of 13

8 public interface Set { // Basic Operations int size(); boolean isempty(); boolean contains(object element); boolean add(object element); // Optional boolean remove(object element); // Optional Iterator iterator(); // These are Bulk Operations boolean containsall(collection mycollection); boolean addall(collection mycollection); // Optional boolean removeall(collection mycollection); // Optional boolean retainall(collection mycollection); // Optional void clear(); // Optional // These are Array Operations Object[] toarray(); Object[] toarray(object a[]); General Purpose Set Implementations 1. HashSet stores its elements in a hash table. This implementation offers excellent performance 2. TreeSet stores its elements in a red-black tree. This implementation guarantees the order of iteration. Example: Removing duplicates from a collection mycolelction. We create a set initially containing all the elements in mycollection. This cannot contain duplicates by definition. Collection distinctcollection = new HashSet(myCollection); 8 of 13

9 The following are some of the methods that can be used with Set. 1. size(): 2. isempty(): 3. add(): 4. remove(): 5. iterator(): a. This returns the number of elements in a set. a. This returns true if the set is empty. a. This adds a new element to the set if it was not present already. It returns a true to indicate that the element was added or false if not. a. This removes the specified element from the set if it is present and returns a true. It returns false if the element was not removed. a. This returns an iterator of the set. Example: To write a Java program takes the words in its argument list (could be long or short) and prints out any duplicate words present, the number of distinct words, as well as a list of the words with duplicates eliminated. import java.util.*; public class DetectAndRemoveDuplicates { public static void main(string args[]) { Set myset = new HashSet(); for (int k = 0; k < args.length; k++) if (!myset.add(args[k])) System.out.println("Duplicate Found -- "+args[i]); System.out.println("Set Size: "+myset.size()+" Distinct Words Found -- "+ myset); I urge you to execute this program and examine the results. This is an incredibly powerful method that performs an otherwise relatively complicated task rather simply. Example: To write a Java program takes the words in its argument list (could be long or short) and prints out any duplicate words present in alphabetical order, the number of distinct words, as well as a list of the words with duplicates eliminated. 9 of 13

10 Note that this requirement is quite the same as the earlier example, except that we want the list of words to be displayed in alphabetical order. Now don t rush off to write a fresh program from start. If we use the power of the Java Collection Framework, we would realize that all we need to do is to use the implementation of the set by a TreeSet instead of the earlier HashSet. In the above program, just make the modification in the constructor for the set as follows. Set myset = new TreeSet(); Compile and execute this program to convince yourself that the program would work as intended. This is really powerful stuff. Bulk Operations on Set 1. set1.containsall(set2): a. This returns true if set2 is a subset of set1. 2. set1.addall(set2): a. This makes set1 into the union of set1 and set2. b. The union of two sets is the set containing all the elements found in the two sets. 3. set1.retainall(set2): a. This makes set1 into the intersection of set1 and set2. b. The intersection of two sets is the set containing only those elements that are common in both the sets. 4. set1.removeall(set2): a. This makes set1 into the asymmetric set difference of set1 and set2. b. The set difference of set1 - set2 is the set containing all the elements found in set1 but not in set2. Learning to Use the List Interface In the Java Collection framework, a list is an ordered collection. It is also called a sequence. Lists allow duplicate elements to be present unlike in a set. We can control the place in a list where a new element is to be inserted. Using an integer index, which is used to denote the position of the element in the list, we can access the elements. 10 of 13

11 The List can use the operations inherited from the Collection interface. Some of the other operations included in the List interface are as follows. 1. Positional Access: This is used to manipulate the elements based on their numerical position in the list. 2. Search: This is used to search for a specified object in the list and return its numerical position. 3. List Iteration: This extends Iterator mechanism for enabling sequential traversal in a list.. 4. Range-View: This is used to carry out arbitrary range operations on the list. The List interface is displayed below. public interface List extends Collection { // Positional Access Object get(int index); // Optional Object set(int index, Object element); // Optional void add(int index, Object element); // Optional Object remove(int index); // Optional abstract boolean addall(int index, Collection mycollection); // Search int indexof(object myobject); int lastindexof(object myobject); // Iteration ListIterator listiterator(); ListIterator listiterator(int index); // Range-View List sublist(int from, int to); General Purpose List Implementations The following are the two general purpose List implementations. 1. ArrayList 2. LinkedList The following are some methods that can be used with List. 11 of 13

12 1. remove(): 2. add(): 3. addall(): a. This method is used to remove the first occurrence of the specified element from the list. a. Append the specified item at the end of the list. a. Append the specified item at the end of the list. 4. ListIterator(): a. The iterator operation in a list returns the elements of the list in proper sequence b. It allows us to traverse the list in either direction, modify the list during iteration, and obtain the current position of the iterator 5. hasnext(), hasprevious(), next(), previous(): a. They are all inherited by ListIterator() and work the same way as for the other interfaces There are other methods like get(), set(), and remove() that can be used with lists. It would be a good idea to learn how to concatenate two lists, to check if two lists contain the same elements in the same order, and access elements according their positions in a list. There are far too many methods in this interface. A good way of developing competencies is to solve problems that require the use of various methods, rather than listing the methods and memorizing what they do. Tutorials on List Interface There are a number of good tutorials on YouTube. 1. Cave of Programming tutorial is at 2. Authentic one at Oracle Site Other Interfaces in Collection There are other interfaces that are also very powerful and useful in developing applications. They are: 1. The Map Interface 12 of 13

13 I recommend that you go through the tutorial at 2. The SortedSet Interface I recommend that you go through the tutorial at 3. The SortedMap Interface I recommend that you go through the tutorial at 13 of 13

CS Ananda Gunawardena

CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

9/16/2010 CS Ananda Gunawardena

9/16/2010 CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

CONTAİNERS COLLECTİONS

CONTAİNERS COLLECTİONS CONTAİNERS Some programs create too many objects and deal with them. In such a program, it is not feasible to declare a separate variable to hold reference to each of these objects. The proper way of keeping

More information

Java Collections Framework: Interfaces

Java Collections Framework: Interfaces Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection Interface The List Interface The Iterator Interface The ListIterator

More information

Class 32: The Java Collections Framework

Class 32: The Java Collections Framework Introduction to Computation and Problem Solving Class 32: The Java Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To introduce you to the data structure classes that come

More information

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1 Topic #9: Collections CSE 413, Autumn 2004 Programming Languages http://www.cs.washington.edu/education/courses/413/04au/ If S is a subtype of T, what is S permitted to do with the methods of T? Typing

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

Generic classes & the Java Collections Framework. *Really* Reusable Code

Generic classes & the Java Collections Framework. *Really* Reusable Code Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers

More information

The Java Collections Framework and Lists in Java Parts 1 & 2

The Java Collections Framework and Lists in Java Parts 1 & 2 The Java Collections Framework and Lists in Java Parts 1 & 2 Chapter 9 Chapter 6 (6.1-6.2.2) CS 2334 University of Oklahoma Brian F. Veale Groups of Data Data are very important to Software Engineering

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com 2 Disclaimer & Acknowledgments Even though Sang Shin is a full-time employee

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

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

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 Course Name: Advanced Java Lecture 8 Topics to be covered Collections Introduction A collection, sometimes called a container, is simply an object that groups multiple elements into a single unit. Collections

More information

Sets and Maps. Part of the Collections Framework

Sets and Maps. Part of the Collections Framework Sets and Maps Part of the Collections Framework The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection int size( ); boolean isempty( ); boolean contains(object

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

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code. Lecture 15 Summary Collections Framework Iterable, Collections, Set Map Collections class Comparable and Comparator By the end of this lecture, you will be able to use different types of Collections and

More information

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces Taking Stock IE170: Algorithms in Systems Engineering: Lecture 7 Jeff Linderoth Department of Industrial and Systems Engineering Lehigh University January 29, 2007 Last Time Practice Some Sorting Algs

More information

Introduction to Collections

Introduction to Collections Module 3 COLLECTIONS Introduction to Collections > A collection sometimes called a container is simply an object that groups multiple elements into a single unit. > Collections are used to store, retrieve,

More information

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

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel) Programmieren II Collections Alexander Fraser fraser@cl.uni-heidelberg.de (Based on material from T. Bögel) May 28, 2014 1 / 46 Outline 1 Recap Paths and Files Exceptions 2 Collections Collection Interfaces

More information

Generic Programming. *Really* reusable code

Generic Programming. *Really* reusable code Generic Programming *Really* reusable code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers to create data structures

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University C O P Y R I G H T S 2 0 1 5 E O M, H Y E O N S A N G A L L R I G H T S R E S E R V E D - Containers - About Containers

More information

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help Overview Package Class Use Tree Deprecated Index Help PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes SUMMARY: NESTED FIELD CONSTR METHOD DETAIL: FIELD CONSTR METHOD Página 1 de 30 Java TM 2 Platform

More information

Generics Collection Framework

Generics Collection Framework Generics Collection Framework Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Generics

More information

Lecture 6 Collections

Lecture 6 Collections Lecture 6 Collections Concept A collection is a data structure actually, an object to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util

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

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data 1 JAVA PROGRAMMERS GUIDE LESSON 1 File: JGuiGuideL1.doc Date Started: July 10, 2000 Last Update: Jan 2, 2002 Status: proof DICTIONARIES, MAPS AND COLLECTIONS We have classes for Sets, Lists and Maps and

More information

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14 MINI-MAX USING TREES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 Spring 2014 2 Important Dates. April 10 --- A4 due (Connect 4, minimax, trees) April 15 --- A5 due (Exercises on different topics,

More information

COMP6700/2140 Abstract Data Types: Queue, Set, Map

COMP6700/2140 Abstract Data Types: Queue, Set, Map COMP6700/2140 Abstract Data Types: Queue, Set, Map Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU 19 April 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140

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

Generics and collections

Generics and collections Generics From JDK 1.5.0 They are similar to C++ templates They allow to eliminate runtime exceptions related to improper casting (ClassCastException) Traditional approach public class Box { private Object

More information

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description java.lang Interface Iterable Type Parameters: T - the type of elements returned by the iterator Iterator iterator() Returns an iterator over a set of elements of type T. java.util Interface Iterator

More information

ArrayList. Introduction. java.util.arraylist

ArrayList. Introduction. java.util.arraylist ArrayList Introduction In this article from my free Java 8 course, I will be giving you a basic overview of the Java class java.util.arraylist. I will first explain the meaning of size and capacity of

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

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

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList This article discusses the main classes of Java Collection API. The following figure demonstrates the Java Collection framework. Figure

More information

EECS 2011 M: Fundamentals of Data Structures

EECS 2011 M: Fundamentals of Data Structures EECS 2011 M: Fundamentals of Data Structures Suprakash Datta Office: LAS 3043 Course page: http://www.eecs.yorku.ca/course/2011m Also on Moodle S. Datta (York Univ.) EECS 2011 W18 1 / 19 Iterators and

More information

CS61B Lecture #17. Last modified: Mon Oct 1 13:40: CS61B: Lecture #17 1

CS61B Lecture #17. Last modified: Mon Oct 1 13:40: CS61B: Lecture #17 1 CS61B Lecture #17 Last modified: Mon Oct 1 13:40:29 2018 CS61B: Lecture #17 1 Topics Overview of standard Java Collections classes Iterators, ListIterators Containers and maps in the abstract Amortized

More information

Tha Java Programming Language

Tha Java Programming Language Tha Java Programming Language Kozsik Tamás (2000-2001) kto@elte.hu http://www.elte.hu/~k to/ III. Arrays, collections and other baseclasses Some of the baseclasses Object String StringBuffer Integer, Double,...

More information

An Interface with Generics

An Interface with Generics Generics CSC207 Software Design Generics An Interface with Generics Generics class foo introduces a class with a type parameter T. introduces a type parameter that is required to be

More information

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming Frameworks 1 Framework Set of cooperating classes/interfaces Structure essential mechanisms of a problem domain Programmer can extend framework classes, creating new functionality Example: Swing package

More information

boolean add(object o) Method Description (from docs API ) Method Description (from docs API )

boolean add(object o) Method Description (from docs API ) Method Description (from docs API ) Interface Collection Method Description (from docs API ) boolean add(object o) boolean addall(collection c) void clear() ensures that this collection contains the specified element adds all of the elements

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

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

Lecture 6: ArrayList Implementation

Lecture 6: ArrayList Implementation Lecture 6: ArrayList Implementation CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Programming Assignment Weak AI/Natural Language Processing: Generate text by building frequency lists based

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

Collections. The Java Collections Framework. The Interfaces

Collections. The Java Collections Framework. The Interfaces Collections A collection (sometimes called a container) is an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data, and to transmit data

More information

Interfaces, collections and comparisons

Interfaces, collections and comparisons תכנות מונחה עצמים תרגול מספר 4 Interfaces, collections and comparisons Interfaces Overview Overview O Interface defines behavior. Overview O Interface defines behavior. O The interface includes: O Name

More information

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Wrapper classes. Wrapper classes Java Collections Engi- 5895 Hafez Seliem Wrapper classes Provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being

More information

Java Collections. Engi Hafez Seliem

Java Collections. Engi Hafez Seliem Java Collections Engi- 5895 Hafez Seliem Wrapper classes Provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ ABSTRACT DATATYPES 2 Abstract Datatype (ADT)

More information

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 36. Collections Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Arrays Class Interface Collection and Class Collections ArrayList Class Generics LinkedList Class Collections Algorithms

More information

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures Abstract Data Types (ADTs) Class #08: Linear Data Structures Software Design III (CS 340): M. Allen, 08 Feb. 16 An ADT defines a kind of computational entity: A set of objects, with possible values A set

More information

11. Collections of Objects

11. Collections of Objects 11. Collections of Objects 1 Arrays There are three issues that distinguish arrays from other types of containers: efficiency, type, and the ability to hold primitives. When you re solving a more general

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2015S-05 Abstract Data Types and Lists David Galles Department of Computer Science University of San Francisco 05-0: Abstract Data Types Recall that an Abstract 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

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

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

CS S-05 Abstract Data Types and Lists 1

CS S-05 Abstract Data Types and Lists 1 CS245-2016S-05 Abstract Data Types and Lists 1 05-0: Abstract Data Types Recall that an Abstract Data Type is a definition of a type based on the operations that can be performed on it. An ADT is an interface

More information

Case Study: Debugging a Discovered Specification for java.util.arraylist by Using Algebraic Interpretation

Case Study: Debugging a Discovered Specification for java.util.arraylist by Using Algebraic Interpretation Case Study: Debugging a Discovered Specification for java.util.arraylist by Using Algebraic Interpretation Technical Report CU-CS-970-04 Johannes Henkel and Amer Diwan {henkel,diwan}@cs.colorado.edu February

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

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 22 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5 CSCI 6234 Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship George Blankenship 1 Java Topics Running Java programs Stream I/O New features George Blankenship 2 Running

More information

JAVA COLLECTION FRAMEWORK & SETS

JAVA COLLECTION FRAMEWORK & SETS JAVA COLLECTION FRAMEWORK & SETS Ch07.4-5 & Ch10.5 Presentation for use with the textbook 1. Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,

More information

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed 1 1 COMP200 GENERICS OOP using Java, from slides by Shayan Javed 2 ArrayList and Java Generics 3 Collection A container object that groups multiple objects 4 Collection A container object that groups multiple

More information

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one Iterators What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one 9-2 2-2 What is an Iterator? An iterator is an abstract data

More information

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so. CSE 143 Sp04 Midterm 2 Page 1 of 10 Reference information about some standard Java library classes appears on the last pages of the test. You can tear off these pages for easier reference during the exam

More information

Pieter van den Hombergh Richard van den Ham. February 8, 2018

Pieter van den Hombergh Richard van den Ham. February 8, 2018 Pieter van den Hombergh Richard van den Ham Fontys Hogeschool voor Techniek en Logistiek February 8, 2018 /FHTenL February 8, 2018 1/16 Collection Zoo The basic collections, well known in programming s

More information

SSJ User s Guide. Package simevents Simulation Clock and Event List Management

SSJ User s Guide. Package simevents Simulation Clock and Event List Management SSJ User s Guide Package simevents Simulation Clock and Event List Management Version: December 21, 2006 This package provides the simulation clock and tools to manage the future events list. These are

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

CMSC 202H. Containers and Iterators

CMSC 202H. Containers and Iterators CMSC 202H Containers and Iterators 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

More information

Lecture 4. The Java Collections Framework

Lecture 4. The Java Collections Framework Lecture 4. The Java s Framework - 1 - Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 2 - Learning Outcomes From this lecture you should

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

Get started with the Java Collections Framework By Dan Becker

Get started with the Java Collections Framework By Dan Becker Get started with the Java Collections Framework By Dan Becker JavaWorld Nov 1, 1998 COMMENTS JDK 1.2 introduces a new framework for collections of objects, called the Java Collections Framework. "Oh no,"

More information

EXAMINATIONS 2016 TRIMESTER 2

EXAMINATIONS 2016 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2016 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

A simple map: Hashtable

A simple map: Hashtable Using Maps A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable, use: table.put(key, value); To retrieve a value from

More information

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Implementations I 1 Agenda Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Stack and queues Array-based implementations

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 PROGRAMMING COURSE NO. IT-705(A) SECTION - A

JAVA PROGRAMMING COURSE NO. IT-705(A) SECTION - A Q1. Define the following terms: JAVA PROGRAMMING COURSE NO. IT-705(A) SECTION - A i. Event An event in Java is an object that is created when something changes within a graphical user interface. If a user

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

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , CSE 143 Lecture 26 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, 15.3-15.4, 16.4-16.5 slides created by Marty Stepp, adapted by Alyssa Harding

More information

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017 Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek June 8, 2017 /FHTenL June 8, 2017 1/19 Collection Zoo The basic collections, well known in programming s

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

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

Java Collections Framework. 24 April 2013 OSU CSE 1

Java Collections Framework. 24 April 2013 OSU CSE 1 Java Collections Framework 24 April 2013 OSU CSE 1 Overview The Java Collections Framework (JCF) is a group of interfaces and classes similar to the OSU CSE components The similarities will become clearly

More information

Object-Oriented Programming in the Java language

Object-Oriented Programming in the Java language Object-Oriented Programming in the Java language Part 6. Collections(1/2): Lists. Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Just before we start Generics Generics are a

More information

INTRODUCTION TO DATA AND PROCEDURE

INTRODUCTION TO DATA AND PROCEDURE INTRODUCTION TO DATA AND PROCEDURE In this book, our goal is to understand computation. In particular, we want to be able to take any computational problem and produce a technique for solving it that is

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

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS T E W H A R E W Ā N A N G A O T E Student ID:....................... Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2015 TRIMESTER 2 COMP103 INTRODUCTION

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

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 14 Array Wrap-Up Outline Problem: How can I store information in arrays without complicated array management? The Java language supports ArrayLists

More information

List... NOTE We use List as illustrative example of collections Study the others from textbook!

List... NOTE We use List as illustrative example of collections Study the others from textbook! List... NOTE We use List as illustrative example of collections Study the others from textbook! 25 What is a List? A List is an ordered Collection (sometimes called a sequence) Lists may contain duplicate

More information

Lists. The List ADT. Reading: Textbook Sections

Lists. The List ADT. Reading: Textbook Sections Lists The List ADT Reading: Textbook Sections 3.1 3.5 List ADT A list is a dynamic ordered tuple of homogeneous elements A o, A 1, A 2,, A N-1 where A i is the i-th element of the list The position of

More information

EXAMINATIONS 2017 TRIMESTER 2

EXAMINATIONS 2017 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2017 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 slides adapted from Marty Stepp and Hélène Martin http://www.cs.washington.edu/143/ Related classes Consider classes for

More information

Collections and Maps

Collections and Maps Software and Programming I Collections and Maps Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Array Lists Enhanced for Loop ArrayList and LinkedList Collection Interface Sets and

More information

List ADT. Announcements. The List interface. Implementing the List ADT

List ADT. Announcements. The List interface. Implementing the List ADT Announcements Tutoring schedule revised Today s topic: ArrayList implementation Reading: Section 7.2 Break around 11:45am List ADT A list is defined as a finite ordered sequence of data items known as

More information

CSC 1052 Algorithms & Data Structures II: Lists

CSC 1052 Algorithms & Data Structures II: Lists CSC 1052 Algorithms & Data Structures II: Lists Professor Henry Carter Spring 2018 Recap Collections hold and access elements based on content Order and index no longer considered Comparable elements implement

More information

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2012 MID YEAR COMP103 Introduction to Data

More information