COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

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

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

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

CONTAİNERS COLLECTİONS

Sets and Maps. Part of the Collections Framework

Algorithms. Produced by. Eamonn de Leastar

9/16/2010 CS Ananda Gunawardena

CS Ananda Gunawardena

Generics Collection Framework

Software 1 with Java. Recitation No. 6 (Collections)

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

DM550 Introduction to Programming part 2. Jan Baumbach.

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

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

CMSC 202H. Containers and Iterators

Lecture 6 Collections

תוכנה 1 מבני נתונים גנריים

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

CSC 1214: Object-Oriented Programming

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

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

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

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

Class 32: The Java Collections Framework

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

What is the Java Collections Framework?

Collections and Maps

Collections Questions

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

DM550 Introduction to Programming part 2. Jan Baumbach.

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

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

Java Collections Framework reloaded

Collections Framework: Part 2

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

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

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

Collections (Java) Collections Framework

USAL1J: Java Collections. S. Rosmorduc

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

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

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

תוכנה 1 מבני נתונים גנריים

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.

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

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

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

CMSC 202. Containers

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

Collections, Maps and Generics

A simple map: Hashtable

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

Object-Oriented Programming with Java

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

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

Interfaces, collections and comparisons

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

Week 4, Wednesday (Spring 2015). Dr. Yoder. Sec 051. Page 1 of 5

Tha Java Programming Language

PIC 20A Collections and Data Structures

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

Principles of Software Construction: Objects, Design and Concurrency. More design patterns and Java Collections. toad

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Computer Science II (Spring )

CMSC 132: Object-Oriented Programming II

//instance variables //methods. Foo x = new Foo(); Interface: also a type of objects public interface Bar {

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

COSC 123 Computer Creativity. Java Lists and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Advanced Programming Generics Collections

Introduction to Collections

Java Magistère BFA

Distributed Systems Recitation 1. Tamim Jabban

CS11 Java. Winter Lecture 8

Java Collections Framework

Fundamental language mechanisms

An Interface with Generics

Overview of Java s Support for Polymorphism

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

Java Collections Framework. 24 April 2013 OSU CSE 1

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

Java Collection Framework

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

CS2110: Software Development Methods. Maps and Sets in Java

ArrayList. Introduction. java.util.arraylist

Java Language Features

COMP-202. Generics. COMP Generics, 2013 Jörg Kienzle and others

Parametric polymorphism and Generics

The Java Collections Framework. Chapters 7.5

11/27/12. CS202 Fall 2012 Lecture 11/15. Hashing. What: WiCS CS Courses: Inside Scoop When: Monday, Nov 19th from 5-7pm Where: SEO 1000

CS108, Stanford Handout #8. Java Generics

Topic 10: The Java Collections Framework (and Iterators)

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

CS2110: Software Development Methods. Maps and Sets in Java

Programming Languages and Techniques (CIS120)

Announcements/Follow-ups

Interfaces and Collections

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

+ Abstract Data Types

Interfaces. An interface defines a set of methods. An interface declaration contains signatures, but no implementations.

Transcription:

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 Operations Generics

COLLECTIONS What is a collection?

COLLECTIONS What is a collection? a group of things that have been gathered [http://www.merriam-webster.com/dictionary/collection] What is a collection in Java? are containers of Objects which by polymorphism can hold any class that derives from Object GENERICS make containers aware of the type of objects they store from Java 1.5

COLLECTIONS. EXAMPLE. JAVA < 1.5 static public void main(string[] args) { ArrayList argslist = new ArrayList(); argslist.add(args.length); for(string str : args) { argslist.add(str); if(argslist.contains("java") { System.out.println("Found Java word in collection"); String first = (String)argsList.get(0); System.out.println("First: " + first);

COLLECTIONS. EXAMPLE. JAVA 1.5 static public void main(string[] args) { ArrayList<String> argslist = new ArrayList<String>(); argslist.add(args.length); // ERROR way? for(string str : args) { argslist.add(str); if(argslist.contains("java") { System.out.println("Found Java word in collection"); String first = argslist.get(0); // NO CASTING System.out.println("First: " + first);

GENERICS Introducesd in Java 1.5 Allows class and methods definitions with parameters for types Classes or methods that have type parameters are called parameterized class or generic definitions, or, simply, generics Can be defined by Java libraries user defined

GENERICS. EXAMPLES FROM JAVA LIBRARY public interface List<E> { void add(e x); Iterator<E> iterator(); public interface Iterator<E> { E next(); boolean hasnext(); public interface Map<K,V> { V put(k key, V value);

GENERICS. EXAMPLES. USER DEFINED public class MyPair<T1, T2> { private T1 leftvalue; private T2 rightvalue; public T1 getleftvalue(){ return leftvalue; public MyPair (T1 t1, T2 t2){ leftvalue = t1; rightvalue = t2; public String tostring(){ return "(" + leftvalue + ", + rightvalue + ")"; public T2 getrightvalue() { return rightvalue; public void setrightvalue(t2 rightvalue) { this.rightvalue = rightvalue; public void setleftvalue(t1 leftvalue) { this.leftvalue = leftvalue;

GENERICS. EXAMPLES. USER DEFINED public class Test { public static void main(string[] args) { MyPair<Integer, Integer> p1 = new MyPair<Integer, Integer>(10, 8); System.out.println("p1: " + p1); MyPair<String, Double> p2 = new MyPair<String, Double>("Coffe", 1.5); System.out.println("p2: " + p2); Output p1: (10, 8) p2: (Coffe, 1.5)

GENERICS Syntax class name<t1, T2,..., Tn> { /*... */ Parameterized Types can also substitute a type parameter (i.e., K or V) with a parameterized type Example MyPair< String, ArrayList<Characters>> p3; Dyamond operator <> from Java 1.7 can determine the type arguments from the context Example MyPair< String, ArrayList<Characters>> p3 = new MyPair< String, ArrayList<Characters>>(); Becomes: MyPair< String, ArrayList<Characters>> p3 = new MyPair<>();

GENERICS METHODS Methods that introduce their own type parameters Static and non-static generic methods are allowed Example public class Util { public static <K, V> boolean compare(mypair<k, V> p1, MyPair<K, V> p2) { return p1.getrightvalue().equals(p2.getrightvalue()) && p1.getleftvalue().equals(p2.getleftvalue()); Call public class Test { public static void main(string[] args) { MyPair<Integer, Integer> p1 = new MyPair<Integer, Integer>(10, 8); MyPair<Integer, Integer> p3 = new MyPair<Integer, Integer>(15, 8); System.out.println("p1=p3? " + Util.compare(p1, p3));

GENERICS METHODS Bounded Type Parameters The restriction of the type can be aslo done in case of classes restrict the types that can be used as type arguments in a parameterized type Example public class Util { public static <K extends Number, V extends Number> boolean comparejustnumbers(mypair<k, V> p1, MyPair<K, V> p2) { return p1.getrightvalue().equals(p2.getrightvalue()) && p1.getleftvalue().equals(p2.getleftvalue()); Correct call is? public static void main(string[] args) { MyPair<Integer, Integer> p1 = new MyPair<Integer, Integer>(10, 8); MyPair<String, Double> p2 = new MyPair<String, Double>("Coffee", 1.5); MyPair<Integer, Integer> p3 = new MyPair<Integer, Integer>(15, 8); MyPair<String, Double> p4 = new MyPair<String, Double>("Coffee", 1.5); System.out.println("p1=p3? " + Util.compareJustNumbers(p1, p3)); System.out.println("p2=p4? " + Util.compareJustNumbers(p2, p4));

GENERICS Bounded Type Parameters Also accepts multiple bounds <T extends B1 & B2 & B3> Example class D <T extends A & B & C> { /*... */

GENERICS What happends when a generic type is instantiated?

GENERICS What happends when a generic type is instantiated? There is no real copy for each parameterized type (Unlike Templates in C++) Compile time check (e.g. List<Integer> adds only Integers) Compiler adds run-time casting (e.g. pulling item from List<Integer> goes through run-time casting to Integer) At run-time, the parameterized types (e.g. <T>) are Erased this technique is called Erasure E.g. List<String> is converted to List E.g. String t = stringlist.iterator().next() is converted to String t = (String) stringlist.iterator().next() What would be the result of the following code? List <String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getclass());

COLLECTIONS A collection is an object that groups multiple elements into a single unit Java propose a collection framework Unified architecture for representing and manipulating collections. A collections framework contains three things Interfaces Each defines the operations and contracts for a particular type of collection (List, Set, Queue, etc) Idea: when using a collection object, it s sufficient to know its interface Implementations Reusable classes that implement above interfaces (e.g. LinkedList, HashSet) Algorithms Useful polymorphic methods for manipulating and creating objects whose classes implement collection interfaces Sorting, index searching, reversing, replacing etc.

COLLECTIONS

COLLECTIONS Collection interface Defines fundamental methods int size(); boolean isempty(); boolean contains(object element); boolean add(object element); // Optional boolean remove(object element); // Optional Iterator iterator(); These methods are enough to define the basic behavior of a collection Provides an Iterator to step through the elements in the Collection

COLLECTION ITERATOR An Iterator is an object that enables to traverse through a collection and to remove elements from the collection selectively, if desired iterator() method is used to obtain an iterator for a collection Iterator interface public interface Iterator<E> { boolean hasnext(); E next(); void remove(); //optional

COLLECTION ITERATOR Display a collection using an iterator List<String> list = new ArrayList<>(); list.add("course");list.add("four"); list.add("java"); for (Iterator<String> it = list.iterator(); it.hasnext();){ System.out.println("List element: " + it.next()); Display a collectio using for-each statement List<String> list = new ArrayList<>(); list.add("course");list.add("four"); list.add("java"); for (String element: list){ System.out.println("List element: " + element);

COLLECTION For-each statement can be used by arrays also. ITERATOR Disadvantage: losing the index position Example: int t[] = { 1, 2, 3, 4 ; Display a collection using // an not iterator using for-each List<String> list = new ArrayList<>(); for (int i = 0; i < t.length; i++) list.add("course");list.add("four"); list.add("java"); System.out.println("El[" + i + "]=" + t[i]); //using for-each for (Iterator<String> it = list.iterator(); it.hasnext();){ for(int el:t){ System.out.println("List System.out.println("El element: " + it.next()); = "+ el); Display a collectio using for-each statement List<String> list = new ArrayList<>(); list.add("course");list.add("four"); list.add("java"); for (String element: list){ System.out.println("List element: " + element);

COLLECTIONS

COOLECTION. LIST INTFACE Java provides 3 concrete classes which implement the list interface Vector ArrayList LinkedList Vectors try to optimize storage requirements by growing and shrinking as required Methods are synchronized (used for Multi threading) ArrayList is roughly equivalent to Vector except that its methods are not synchronized LinkedList implements a doubly linked list of elements Methods are not synchronized

COOLECTION. LIST INTFACE A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for the following: Positional access Manipulates elements based on their numerical position in the list Includes methods such as get, set, add, addall, and remove. Search Searches for a specified object in the list and returns its numerical position. Search methods include indexof and lastindexof. Iteration Extends Iterator semantics to take advantage of the list's sequential nature. The listiterator methods provide this behavior. Range-view The sublist method performs arbitrary range operations on the list.

COOLECTION. LIST INTFACE Example List a1 = new ArrayList(); a1.add("course"); a1.add("programming"); a1.add("iii"); System.out.println(" ArrayList Elements"); System.out.print("\t" + a1); List a2 = new LinkedList(); a2.addall(a1); System.out.print( Element on position 2 in list: + a2.get(2)); a1.set(2, Java ); a1.remove( Programming ) int i = a2.lastindex( III );

COOLECTION. LIST IMPLEMENTATIONS ArrayList low cost random access high cost insert and delete array that resizes if need be LinkedList sequential access low cost insert and delete high cost random access

COLLECTIONS

COLLECTIONS. SET INTERFACE Java provides 2 concrete classes which implement the Set interface HashSet TreeSet The elements cannot be duplicated. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

COLLECTIONS. SET INTERFACE Example int count[] = {34, 22,10,60,30,22; Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i < 5; i++) { set.add(count[i]); System.out.println(set); TreeSet sortedset = new TreeSet<Integer>(set); System.out.println("The sorted list is:"); System.out.println(sortedSet); System.out.println("The First element of the set is: "+ (Integer)sortedSet.first()); System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());

COLLECTION. HASHSET Find and add elements very quickly uses hashing implementation in HashMap Hashing uses an array of linked lists The hashcode() is used to index into the array Then equals() is used to determine if element is in the (short) list of elements at that index No order imposed on elements The hashcode() method and the equals() method must be compatible if two objects are equal, they must have the same hashcode() value

COLLECTION. TREESET Elements can be inserted in any order The TreeSet stores them in order An iterator always presents them in order Default order is defined by natural order objects implement the Comparable interface TreeSet uses compareto(object o) to sort Can use a different Comparator provide Comparator to the TreeSet constructor

COLLECTIONS

COLLECTION. MAP INTERFACE Stores key/value pairs Maps from the key to the value Keys are unique a single key only appears once in the Map a key can map to only one value Values do not have to be unique

COLLECTION. MAP INTERFACE 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()

COLLECTION. MAP INTERFACE Iterating over the keys and values in a Map Set keyset() returns the Set of keys contained in the Map Collection values() returns the Collection of values contained in the Map. this Collection is not a Set, as multiple keys can map to the same value. Set entryset() returns the Set of key-value pairs contained in the Map. Map interface provides a small nested interface called Map.Entry that is the type of the elements in this Set.

COLLECTION. MAP INTERFACE IMPLEMENTATIONS HashMap The keys are a set - unique, unordered Fast TreeMap The keys are a set - unique, ordered Same options for ordering as a TreeSet Natural order (Comparable, compareto(object)) Special order (Comparator, compare(object, Object))

MAP. EXAMPLE Exercise Create a map thet contains the number of appearences of a letter into a word. ex: maria m - 1 times a - 2 times r - 1 times i - 1 times