CS 15-121 Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Lecture 3 Introduction to Collections Advanced Java Programming 1 dr inż. Wojciech Bieniecki
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Collections. What is the Collections framework?  Collections framework provides two things: –implementations of common high-level data structures: e.g.
Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
15-Jun-15 Lists in Java Part of the Collections Framework.
Professor Evan Korth (adapted from Sun’s collections documentation)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Introduction to Java Collections
Data Structures & Java Collections Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 17 Advanced Java Concepts Data Structure Support.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
05 - Containers DRAFT COPY © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
1 Frameworks Part 2. 2 Collections Framework Java API contains library of useful data structures Collections library also serves as framework for adding.
The Java Collections Package C. DeJong Fall 2001.
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java 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.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
COLLECTIONS Byju Veedu s/Collection.html.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
1 Interfaces in Java’s Collection Framework Rick Mercer.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
University of Limerick1 Collections The Collection Framework.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Java Collections CHAPTER 3-February-2003
Java Collections OOP tirgul No
Programming & Data Structures
Introduction to Collections
Introduction to Collections
TCSS 342, Winter 2006 Lecture Notes
Java语言程序设计 马 皓
Introduction to Collections
Part of the Collections Framework
Collections in Java The objectives of this lecture are:
Introduction to Collections
Collections Framework
Introduction to Collections
Part of the Collections Framework
Java Generics & Iterators
Presentation transcript:

CS 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, and to transmit data from one method to another.  Examples: ◦ Arrays, hashtables, vector, set, map, tree

 ArrayList is a java collection that allows management of a dynamic list collection  Eg: ◦ ArrayList A = new ArrayList(); ◦ A.add(new Integer(10)); ◦ System.out.println(A.get(0)); ◦ If (A.contains(new Integer(10))) { ….} ◦ A.remove(0);

See others at

 Given an ArrayList A of objects write a method removeDups that removes all duplicate elements from the list

 The Collections Framework ◦ A unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. ◦ Reduces programming effort while increasing performance. ◦ Allows for interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters software reuse. ◦

 Interfaces: abstract data types representing collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages like Java, these interfaces generally form a hierarchy.  Implementations: concrete implementations of the collection interfaces. In essence, these are reusable data structures.  Algorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. These algorithms are said to be polymorphic because the same method can be used on many different implementations of the appropriate collections interface. In essence, algorithms are reusable functionality.

 A Java interface contains specifications for a known set of functions.  These functions are to be implemented by classes ◦ Eg: public class foo implements List { }  Interfaces from java collections framework

Java does not allow above Here is a hack

 Reduces programming effort  Increases program speed and quality  Allows interoperability among unrelated APIs  Reduces the effort to learn and use new APIs:  Reduces effort to design new APIs  Supports software reuse

 Set is a collection with NO order  Similar to the Mathematical Abstraction of Set public interface Set { // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); Iterator iterator(); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); //Array Operations Object[] toArray(); Object[] toArray(Object a[]); }  Example: Collections noDups = new HashSet(c );

import java.util.*; public class FindDups { public static void main(String args[]) { Set s = new HashSet(); for (int i=0; i<args.length; i++) if (!s.add(args[i])) System.out.println("Duplicate detected: "+args[i]); System.out.println(s.size()+" distinct words detected: "+s); }  What is the output of : java FindDups I am sam sam I am

 s1.containsAll(s2) : Returns true if s2 is a subset of s1  s1.addAll(s2) : Transforms s1 into the union of s1 and s2  s1.retainAll(s2) : Transforms s1 into the intersection of s1 and s2  s1.removeAll(s2) : Transforms s1 into the (asymmetric) set difference of s1 and s2  Exercise: Write a program that will read a line of words and list those ones that occur once and those that occur more than once. ◦ Example: java FindDups i am Sam Sam I am ◦ Unique words: [i, I ] ◦ Duplicate words: [Sam, am]  More info at: ◦

 List is an ordered Collection (sometimes called a sequence). List Collection  Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for: Index based Access: manipulate elements based on their numerical position in the list. Search: search for a specified object in the list and return its index position. List Iteration: extend Iterator semantics to take advantage of the list's sequential nature. Range-view: perform arbitrary range operations on the list.

public interface List extends Collection { // index based Access Object get(int index); Object set(int index, Object element); // Optional void add(int index, Object element); Object remove(int index); abstract boolean addAll(int index, Collection c); // Search int indexOf(Object o); int lastIndexOf(Object o); ListIterator listIterator(); ListIterator listIterator(int index); // Range-view List subList(int from, int to); }

 Two important List implementations ◦ ArrayList ◦ LinkedList

 Iterators allow collection to be accessed using a pre-defined “pointer” public interface ListIterator extends Iterator { boolean hasNext(); Object next(); boolean hasPrevious(); Object previous(); int nextIndex(); int previousIndex(); void remove(); // Optional void set(Object o); void add(Object o); }

 What is the purpose of the following code? for (ListIterator i=L.listIterator(l.size()); i.hasPrevious(); ) { Foo f = (Foo) i.previous();... } ◦ Steps through a list backwards

 Maps keys to values  Each Key can map to a unique value public interface Map { // Basic Operations Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk Operations void putAll(Map t); void clear(); // Collection Views public Set keySet(); public Collection values(); public Set entrySet(); // Interface for entrySet elements public interface Entry { Object getKey(); Object getValue(); Object setValue(Object value); } }

 HashTable is an implementation of the Map interface  An example of generating a frequency table import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); // Initialize frequency table from command line for (int i=0; i<args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m.size()+" distinct words detected:"); System.out.println(m); }

 The Java provides a reusable algorithms that can operate on a List. The following algorithms are provided. ◦ Sorting Sorting ◦ Shuffling Shuffling ◦ Routine Data Manipulation Routine Data Manipulation ◦ Searching Searching ◦ Composition Composition ◦ Finding Extreme Values Finding Extreme Values

 A List can be sorted according to its natural ordering  Java uses an optimized merge sort ◦ Fast: runs in n log(n) time ◦ Runs faster on nearly sorted lists. ◦ Stable: It doesn't reorder equal elements.

import java.util.*; public class Sort { public static void main(String[] args) { List list = new ArrayList(); list.add(“guna”); list.add(“bob”); //etc… Collections.sort(list); System.out.println(list); }

 Shuffle algorithm does the opposite of sort  It puts elements in the list in a random order so that each element is equally likely  Applications ◦ Shuffle a card deck  Example: ◦ Collections.shuffle(list);

 Reverse ◦ reverses the order of the elements in a List.  Fill ◦ overwrites every element in a List with the specified value. This operation is useful for reinitializing a List.  Copy ◦ takes two arguments, a destination List and a source List, and copies the elements of the source into the destination, overwriting its contents. The destination List must be at least as long as the source. If it is longer, the remaining elements in the destination List are unaffected.  Swap ◦ swaps the elements at the specified positions in a List.  addAll ◦ adds all the specified elements to a Collection. The elements to be added may be specified individually or as an array. Source: java.sun.com

 The binary search algorithm provides a way to search for a key.  Example ◦ int pos = Collections.binarySearch(list, key); ◦ if (pos < 0) l.add(-pos-1);

 Frequency ◦ counts the number of times the specified element occurs in the specified collection  Disjoint ◦ determines whether two Collections are disjoint; that is, whether they contain no elements in common