Lecture 3 Introduction to Collections Advanced Java Programming 1 dr inż. Wojciech Bieniecki

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Collections Chapter Java Collection Frameworks The Java collection framework is a set of utility classes and interfaces. Designed for working with.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Data Structures Lecture 2 Fang Yu Department of Management Information Systems National Chengchi University Fall 2011.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L16 (Chapter 22) Java Collections.
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.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
The Java Collections Package C. DeJong Fall 2001.
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
The Java Collections Framework Chapters 7.5. Outline Introduction to the Java Collections Framework Iterators Interfaces, Abstract Classes and Classes.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
COLLECTIONS Byju Veedu s/Collection.html.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
Chapter 18 Java Collections Framework
CSE 373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks; Eclipse.
Data structures Abstract data types Java classes for Data structures and ADTs.
HIT2037- HIT6037 Software Development in Java 22 – Data Structures and Introduction.
Useful Data Structures in C++ and Java. Useful Data Structures in C++ (1) Templates are C++’s mechanism to define abstract objects which can be parameterized.
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.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
Nov 22, 2010IAT 2651 Java Collections. Nov 22, 2010IAT 2652 Data Structures  With a collection of data, we often want to do many things –Organize –Iterate.
Maps Nick Mouriski.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
University of Limerick1 Collections The Collection Framework.
CSE 373 Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks; Eclipse.
Collections Dwight Deugo Nesa Matic
Java Collection Classes Com379PT
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Sixth Lecture ArrayList Abstract Class and Interface
JAVA COLLECTIONS LIBRARY
structures and their relationships." - Linus Torvalds
CS313D: Advanced Programming Language
structures and their relationships." - Linus Torvalds
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Collections Not in our text.
Chapter10 Collections.
Programming Languages
structures and their relationships." - Linus Torvalds
Presentation transcript:

Lecture 3 Introduction to Collections Advanced Java Programming 1 dr inż. Wojciech Bieniecki

Introduction 2 A collection (containter) - an object that groups multiple elements into a single unit. Collections are used to store, retrieve, operate, and communicate aggregated data. Typically, they represent data items that form a natural group, such as: - poker hand (a collection of cards), - mail folder (a collection of letters), - telephone directory (a mapping of names to phone numbers). Collection implementations in early versions of the Java platform included Vector, Hashtable and array. They did not contain a collections framework.

Introduction 3 Collections framework - a unified architecture for representing and manipulating collections. Collections frameworks contain the following: Interfaces – abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. Interfaces generally form a hierarchy. Implementations – concrete implementations of the collection interfaces – reusable data structures. Algorithms – methods that perform computations (searching, sorting, iteration) on objects that implement collection interfaces. Algorithms are polymorphic – the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. Apart from the Java Collections Framework, the best-known examples of collections frameworks are the C++ Standard Template Library (STL) and Smalltalk's collection hierarchy. Historically, collections frameworks have been quite complex, which gave them a reputation for having a steep learning curve. We believe that the Java Collections Framework breaks with this tradition, as you will learn for yourself in this chapter.

Introduction 4 A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following: Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy. Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures. Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

Introduction 5 May reduce programming effort -provides useful high-level data structures and algorithms Advantages of the Java Collections Framework Increases program speed and quality: -high-performance, high-quality implementations of useful data structures and algorithms -A possibility to replace an individual implementation -You may concentrate to programs' quality and performance. Allows interoperability among unrelated APIs Reduces effort to learn and to use new APIs: - Many APIs naturally take collections on input and furnish them as output. Reduces effort to design new APIs Fosters software reuse New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.

Java collections (obsolete) Main operations: add(object) – add the object at the end of the list Java.util.Vector An array of objects. This is a list of objects with array functions 6 add(index, object ) – add the object to the list after the object pointed by index set(index, element) – replaces the object in the index get(index) – returns the object from the index indexOf(obiex ) – searches of the first occurence of the object

Java collections (obsolete) Java.util.Hashtable The dictionary of the objects. It can associate pairs: key (word) with any object. Hashtable c = new Hashtable(); c.put("black", Color.black); c.put("blue", Color.blue); c.put("red", Color.red); c.put("yellow", Color.yellow); c.put("white", Color.white); Color c = (Color) ht.get("blue"); 7 Main operations: put(napis, obiekt) – add a pair to the array get(napis) – returns the object pointed by the key

Java collections (obsolete) Java.util.Stack A stack of the objects. Main operations: empty() – is the stack empty? peek () – returns the object from the to without popping it pop() – pops the object from the top push(object ) – throws the object on the top search(object) – returns the index of the object if it exists on the stack 8

Lists System.out.println("=====lists=====\n"); ArrayList a1 = new ArrayList(); a1.add("dog"); a1.add("cat"); a1.add("dog"); System.out.println(a1); List a2 = new ArrayList(); a2.add("wardrobe"); a2.add("table"); a2.add("wardrobe"); System.out.println(a2); Collection a3 = new ArrayList(); a3.add("brother"); a3.add("sister"); a3.add("brother"); System.out.println(a3); Each list will have three elements - the repetitions are allowed. 9

Sets System.out.println("\n=====sets=====\n"); HashSet b1 = new HashSet(); b1.add("dog"); b1.add("cat"); b1.add("dog"); System.out.println(b1); Set b2 = new HashSet(); b2.add("wardrobe"); b2.add("table"); b2.add("wardrobe"); System.out.println(b2); Collection b3 = new HashSet(); b3.add("brother"); b3.add("sister"); b3.add("brother"); System.out.println(b3); Each list will have the two elements - the repetitions are not allowed. 10

Maps (associative arrays) System.out.println("\n=====associations=====\n"); HashMap c1 = new HashMap(); c1.put("dog","Baton"); c1.put("cat","Fruzia"); c1.put("dog","Fucha"); System.out.println(c1); Map c2 = new HashMap(); c2.put("brother","Maciek"); c2.put("sister","Marta"); c2.put("brother","Marcin"); System.out.println(c2); cat Fruzia, dog Fucha sister Marta, brother Marcin 11

Maps (different keys) System.out.println("\n=====mappings for diff. keys =====\n"); HashMap d1 = new HashMap(); d1.put("Baton","dog"); d1.put("Fruzia","cat"); d1.put("Fucha","dog"); System.out.println(d1); Map d2 = new HashMap(); d2.put("Maciek","brother"); d2.put("Marta","sister"); d2.put("Marcin","brother"); System.out.println(d2); Fruzia cat, Baton dog, Fucha dog Maciek brother, Marta sister, Marcin brother 12

Use of iterator public class Dog { private int nr; Dog(int i) { nr = i; } void print() { System.out.print ("Dog-"+nr+", "); } public String toString() { return "Doggy-" + nr ; } public class Cat { private int nr; Cat(int i) { nr = i; } void print() { System.out.print("Cat-"+nr+", "); } public String toString() { return "Kitty-" + nr ; } 13

Use of iterator ArrayList cats = new ArrayList(); for(int i = 0; i < 4; i++) cats.add(new Cat(i)); cats.add(new Dog(0)); for(int i = 0; i < cats.size(); i++) System.out.print(cats.get(i) + ", "); System.out.println(""); System.out.println("1==========================="); try{ for(int i = 0; i < cats.size(); i++) ((Cat)cats.get(i)).print(); }catch(Exception e) {}` 1=========================== Cat-0, Cat-1, Cat-2, Cat-3 14

Use of iterator System.out.println("2==========================="); ArrayList dogs = new ArrayList(); for(int i=0; i<6;i++) dogs.add(new Dog(i)); Iterator w = dogs.iterator(); while(w.hasNext()) ((Dog)w.next()).print(); System.out.println(""); System.out.println("3==========================="); ListIterator from3 = dogs.listIterator(3); while(from3.hasNext()) ((Dog)from3.next()).print(); System.out.println(""); 2=========================== Dog-0, Dog-1, Dog-2, Dog-3, Dog-4, Dog-5 3=========================== Dog-3, Dog-4, Dog-5 15

Use of iterator System.out.println("4==========================="); dogs.add(1,new Dog(10)); Iterator w1 = dogs.iterator(); while(w1.hasNext()) ((Dog)w1.next()).print(); System.out.println("5==========================="); dogs.set(5,new Dog(25)); Iterator w2 = dogs.iterator(); while(w2.hasNext()) ((Dog)w2.next()).print(); System.out.println(""); 4=========================== Dog-0, Dog-10, Dog-1, Dog-2, Dog-3, Dog-4, Dog-5 5=========================== Dog-0, Dog-10, Dog-1, Dog-2, Dog-3, Dog-25, Dog-5 16

New Java Collections (interface hierarchy) 17 InterfacesHash tables Resizable arrays TreesLinked lists Hash tables + Linked lists SetHashSet TreeSet LinkedHashSet List ArrayList LinkedList Queue ArrayDequeue Dequeue MapHashMap TreeMap LinkedHashMap

Old and new collections 18 (set not included)

Interfaces 19 Collection - the root of the collection hierarchy. Represents any group of objects Used to pass collections around and to manipulate them when maximum generality is desired. Set - a collection that stores unique elements. It models the mathematical set abstraction and is used to represent sets. List – an ordered collection. Lists can contain duplicate elements. It models the mathematical concept of finite sequence. The lists are doubly linked Queue — a collection used to hold multiple elements prior to processing. A Queue provides additional insertion, extraction, and inspection operations. Queues typically, order elements in a FIFO (first-in, first-out) manner. The head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue.

Interfaces 20 Map An object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. The next two core collection interfaces are merely sorted versions of Set and Map SortedSet A set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls. SortedMap A Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.

Traversing Collections 21 for-each Construct for (Object o : collection) System.out.println(o); for (Object o : collection) System.out.println(o); Iterators An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. Use Iterator instead of the for-each construct when you need to: - Remove the current element. The for-each construct hides the iterator, so you cannot call remove. - Iterate over multiple collections in parallel. static void filter(Collection c) { for (Iterator it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); } static void filter(Collection c) { for (Iterator it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); }

Collection operations 22 containsAll — returns true if the target Collection contains all of the elements in the specified Collection. addAll — adds all of the elements in the specified Collection to the target Collection. removeAll — removes from the target Collection all of its elements that are also contained in the specified Collection. retainAll — removes from the target Collection all its elements that are not also contained in the specified Collection. That is, it retains only those elements in the target Collection that are also contained in the specified Collection. clear — removes all elements from the Collection. toArray – allows the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array. Object[] a = c.toArray(); String[] a = c.toArray(new String[0]);