Constraining Type Variables

Size: px
Start display at page:

Download "Constraining Type Variables"

Transcription

1 Constraining Type Variables Type variables can be constrained with bounds. It is often necessary to specify what types can be used in a generic class or method. Consider a generic min method that finds the smallest element in an array list of objects. How can you find the smallest element when you know nothing about the element type? You need to have a mechanism for comparing array elements. One solution is to require that the elements belong to a type that implements the Comparable interface. In this situation, we need to constrain the type variable. public static <E extends Comparable> E min(e[] a) { E smallest = a[0]; for (int i = 1; i < a.length; i++) if (a[i].compareto(smallest) < 0) smallest = a[i]; return smallest; You can call min with a String[] array but not with a Rectangle[] array the String class implements Comparable, but Rectangle does not. Very occasionally, you need to supply two or more type bounds. Then you separate them with the & character, for example <E extends Comparable & Cloneable> The extends keyword, when applied to type variables, actually means extends or implements. The bounds can be either classes or interfaces, and the type variable can be replaced with a class or interface type.

2 Example import java.util.*; public class PairTest2 { public static void main(string[] args) { GregorianCalendar[] birthdays = { new GregorianCalendar(1906, Calendar.DECEMBER, 9), new GregorianCalendar(1815, Calendar.DECEMBER, 10), new GregorianCalendar(1903, Calendar.DECEMBER, 3), new GregorianCalendar(1910, Calendar.JUNE, 22), ; Pair<GregorianCalendar> mm = ArrayAlg.minmax(birthdays); System.out.println("min = " + mm.getfirst().gettime()); System.out.println("max = " + mm.getsecond().gettime()); class ArrayAlg { public static <T extends Comparable> Pair<T> minmax(t[] a) { if (a == null a.length == 0) return null; T min = a[0]; T max = a[0]; for (int i = 1; i < a.length; i++) { if (min.compareto(a[i]) > 0) min = a[i]; if (max.compareto(a[i]) < 0) max = a[i]; return new Pair<T>(min, max);

3 Wildcards It is often necessary to formulate subtle constraints of type variables. Wildcard types were invented for this purpose. There are three kinds of wildcard types: Name Syntax Meaning Wildcard with lower bound? extends B Any subtype of B Wildcard with upper bound? super B Any supertype of B Unbounded wildcard? Any type Because you can t use CustomHolder<Object> as if it were a super-type of CustomHolder<String>, you can t write a method that would process both CustomHolder<Object> and CustomHolder<String>. There is, however, a special way to accomplish this. As part of the generics syntax, a wildcard is introduced, which, when used, basically means any type parameter. Using the wildcard allows you to pass in either stringholder or objectholder. You can read the method parameter type CustomerHolder<?> as a CustomHolder of any type as opposed to of Object type or of String type.

4 Another Example Pair<? extends Employee> denotes any generic Pair type whose type parameter is a subclass of Employee, such as Pair<Manager>, but not Pair<String>. Example: public static void printbuddies(pair<employee> p) { Employee first = p.getfirst(); Employee second = p.getsecond(); System.out.println(first.getName()+ " and " + second.getname() + " are buddies."; you cannot pass a Pair<Manager> to that method. But the solution is simple: use a wildcard type: public static void printbuddies(pair<? extends Employee> p) The type Pair<Manager> is a subtype of Pair<? extends Employee> Subtype Covariance

5 Type of a parameter Type of field Return type Wildcard usages Cannot be used as a type argument for a generic method invocation, a generic class instance creation, a supertype or in the header of reference types Node<?> anynode = new Node<?>(2006, null); //no class QuestionableNode<?> //no, header class SubNode extends Node<?> //no, supertype class ONode implements Comparable<Node<?>> //ok, nested wildcard are permited

6 Subtype covariance and contravariance

7 Unbounded wildcards public static void printlist(list<object> list) { for (Object elem : list) System.out.println(elem + " "); System.out.println(); public static void printlist(list<?> list) { for (Object elem : list) System.out.println(elem + " "); System.out.println();

8 Assignment and Type Erasure Because of type erasure, it is possible to assign a generic class reference to a reference of its nongeneric (legacy) version. Therefore, the following code compiles without error: Vector oldvector; Vector<Integer> intvector; oldvector = intvector; // valid However, though not an error, assigning a reference to a nongeneric class to a reference to a generic class will cause an unchecked compiler warning.

9 Restrictions and Limitations (I) Primitive Types You cannot substitute a primitive type for a type parameter. Thus, there is no Pair<double>, only Pair<Double>. Runtime Type Inquiry Objects in the virtual machine always have a specific nongeneric type. Therefore, all type inquiries yield only the raw type. For example, if (a instanceof Pair<String>) // same as a instanceof Pair really only tests whether a is a Pair of any type. The same is true for the test if (a instanceof Pair<T>) // T is ignored or the cast Pair<String> p = (Pair<String>) a;// can only test that a is a Pair! In the same spirit, the getclass method always returns the raw type. For example, Pair<String> stringpair =...; Pair<Employee> employeepair =...; if (stringpair.getclass() == employeepair.getclass()) // they are equal Arrays You cannot declare arrays of parameterized types, such as Pair<String>[] table = new Pair<String>[10];//ERROR the type is Pair[] You can try to convert it to Object[]: Object[] objarray = table; but if you try to store an element of the wrong type, an ArrayStoreException exception is thrown: objarray[0] = "Hello"; // ERROR--component type is Pair The erasure renders this mechanism ineffective for generic types. For this reason, arrays of parameterized types are outlawed.

10 Restrictions and Limitations (II) Instantiation of Generic Types You cannot instantiate generic types. For example, the following Pair<T> constructor is illegal: public Pair() { first = new T(); second = new T(); // ERROR Type erasure would change T to Object, and surely you don't want to call new Object(). Similarly, you cannot make a generic array: public <T> T[] minmax(t[] a) { T[] mm = new T[2];... // ERROR Type erasure would cause this method to always construct an array Object[2]. However, you can construct generic objects and arrays through reflection, by calling the Class.newInstance and Array.newInstance methods. Static Contexts You cannot reference type variables in static fields or methods. For example, the following clever idea won't work: public class Singleton<T> { public static T getsingleinstance() { // ERROR private static T singleinstance; // ERROR if (singleinstance == null) construct a new instance of T return singleinstance;

11 Implications Subsignature, override-equivalent subsignature: a() subsignature of b() if a() has same signature or signature of a() is same as the erasure of signature of b() Overriding overriding method has a subsignature of the overrided method Overloading Two methods are overloaded if they have the same name but are not override equivalent. static <T> void merge (MyStack<T> s1, MyStack<T> s2) static <T> void merge (MyStack<T> s1, MyStack<? extends T> s2) static <T> void merge (MyStack<T> s1, MyStack<? super T> s2)

12 Collections in Java The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection. The framework provides a convenient API to many of the abstract data types familiar from computer science data structure curriculum: maps, sets, lists, trees, arrays, hashtables and other collections. 12

13 Mathematical Background A collection is the same as the mathematical concept of a set. A set is just a group of unique items, meaning that the group contains no duplicates. The Collections Framework in fact includes a Set interface, and a number of concrete Set classes. Some real-world examples of sets include the following: The set of uppercase letters 'A' through 'Z' The set of nonnegative integers {0, 1, 2... A set of people (friends, employees, clients,...) The set of records returned by a database query The set of Component objects in a Container The set of all pairs The empty set {. These examples show the basic properties of sets: Sets contains only one instance of each item Sets may be finite or infinite Sets can define abstract concepts. A map is a special kind of set. Mathematically speaking, it is a function from one set, the key set, to another set, the value set or a set of pairs. Some examples of maps are: The map of IP addresses to domain names (DNS) A map from keys to database records A dictionary (words mapped to meanings) The conversion from base 2 to base 10 Key set Set of pairs Value set

14 Collection Framework <<interface>> Iterator produce <<interface>> Collection produce <<interface>> Map <<abstract>> Dictionary <<interface>> ListIterator <<interface>> List <<interface>> Set <<abstract>> AbstractMap <<interface>> SortedMap Hashtable <<interface>> Comparator <<abstract>> AbstractCollection HashMap TreeMap Properties <<interface>> Comparable <<abstract>> AbstractList <<abstract>> AbstractSet <<interface>> SortedSet Legend HashSet TreeSet Hashtable Classes in versions 1.0, 1.1 Vector ArrayList <<abstract>> AbstractSequentialList <<interface>> Map HashMap Fundamental interfaces Concrete classes Stack LinkedList

15 Interfaces and Classes for Collections All classes and interfaces of the Collections Framework are generic! Main Interfaces Collection Map Set List SortedMap Concrete Classes SortedSet Interface Implementation Previous classes Set HashSet SortedSet TreeSet List ArrayList LinkedList Vector Stack Map HashMap Hashtable Properties SortedMap TreeMap

16 The java.util.collection Interface Methods Single object operations boolean add(object o) boolean remove(object o) boolean contains(object o) Iterator iterator() int size() boolean isempty() Object groups operations boolean addall(collection<?> c) boolean containall(collection<?> c) boolean removeall(collection<?> c) boolean retainall(collection<?> c) void clear() Array operations Object[] toarray() <T> T[] toarray( T[] a) Meaning Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.) Removes a single instance of the specified element from this collection, if it is present (optional operation). Returns true if this collection contained the specified element. Returns true if this collection contains the specified element. Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned. Returns the number of elements in this collection. Returns true if this collection contains no elements. Adds all of the elements in the specified collection to this collection. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. Returns true if this collection contains all of the elements in the specified collection. Removes all of this collection's elements that are also contained in the specified collection. After this call returns, this collection will contain no elements in common with the specified collection. Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection. Removes all of the elements from this collection (optional operation). The collection will be empty after this method returns. Returns an array containing all of the elements in this collection. If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

17 Methods Methods boolean hasnext() Object next() void remove() The java.util.iterator Interface The iterator() method of the Collection interface returns an Iterator object. With the Iterator interface methods, you can traverse a collection from start to finish and safely remove elements from the underlying collection. The remove() method is optionally supported by the underlying collection. When called, and supported, the element returned by the last next() call is gets-inventory-items-from removed. InventoryBrowser Collection coll =...; Iterator iterator=coll.iterator(); while (iterator.hasnext()) { Object element = iterator.next(); if (removalcheck(element)) { iterator.remove(); Meaning Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.) Returns the next element in the iteration. Removes from the underlying collection the last element returned by this iterator. This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method <<Interface>> Iterator hasnext() : boolean next (): Object InventoryIterator 1..1 creates_an_inventoryiterator 1..1 <<Interface>> Collection iterator() : Iterator gets-inventory-items-from * display * InventoryItem * InventoryCollection iterator() : Iterator

18 Method Declaration Access E get(int index) boolean add(int index, E element) E remove(int index) E set(int index, E element) boolean addall(int index, Collection<? Extends E> c) Object Searching int indexof(object o) int lastindexof(object o) Iteration ListIterator<E> listiterator() ListIterator<E> listiterator(int index) The java.util.list Interface Meaning Returns the element at the specified position in this list. Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list. Replaces the element at the specified position in this list with the specified element (optional operation). Inserts all of the elements in the specified collection into this list at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in this list in the order that they are returned by the specified collection's iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. Returns a list iterator over the elements in this list (in proper sequence). Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next(). An initial call to previous() would return the element with the specified index minus one. Global Operation List<E> sublist(int fromindex, int toindex) Returns a view of the portion of this list between the specified fromindex, inclusive, and toindex, exclusive. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

19 ArrayList ArrayList = Concrete class that implements the List interface using an array with dynamic extension. The random access is relatively fast. Adds methods to the List interface: ArrayList<E>(Collection<E>) Object clone() void ensurecapacity(int) void trimtosize() Allows simulation of object queues, stacks and generally data structures ended by markers: ArrayList<Employee> elements = new ArrayList<Employee>(); elements.add(queueend++, employee); Employee boss = elements.remove(queueinit++); Queue of employees Simulation of a queue with an ArrayList<Employee> Array elements queueinit queueend

20 LinkedList A linked list is a data structure used for collecting a sequence of objects, which allows efficient addition and removal of elements in the middle of the sequence. A linked list consists of a number of nodes, each of which has a reference to which has a reference to the next node. Visiting the elements of a linked list in sequential order is efficient, but random access is not. The Java library provides a LinkedList class. It is a generic class in the java.util package, just like the ArrayList class. The nodes of the LinkedList class store two links: one to the next element and one to the previous one. Such a list is called a doubly linked list. You can use a ListIterator (a generic class) to access elements inside a linked list. You should think of the iterator as pointing between two elements.

21 LinkedList LinkedList = Concrete class that provides an optimal sequential access with removing and insertion operations. The random access is relatively slow (if the randon access is frequent it is better to use an ArrayList). Adds methods to the List interface: addfirst( ) addlast( ) getfirst( ) getlast( ) removefirst( ) removelast( ) Allows simulation of object queues and stacks. Queue of E Simulation of a Queue with a LinkedList LinkedList<E> queue =...; queue.addfirst(element); E object = queue.removelast(); head info next info next info next tail info next

22 Linked Lists In Java double concatenated lists (linked lists) can be used where the object link contains a reference to the previous object, too. LinkedList staff = new LinkedList();..... Iterator it = staff.iterator(); for (int i=0; i<100; i++) System.out.println(it.next()); it.remove(); ListIterator has a method add different from that in Collection: ListIterator iter= staff.listiterator(); iter.next(); iter.add( Mary ); iter.next(); Object oldvalue = iter.next(); iter.set(newvalue); LinkedList first Link Link Link Link data next prev data next prev.... data next prev data next prev The objects Iterator know when the list changes. LinkedList lista =.... ; ListIterator it1 = lista.listiterator(); ListIterator it2 = lista.listiterator(); it1.next(); it1.remove(); it2.next(); 22

23 ListIterator 1. Initially, the iterator points before the first element. 2. You can move the iterator position with the next method: iterator.next(); The next method throws a NoSuchElementException if you are already past the end of the list. 3. You should always call the method hasnext before calling next - it returns true if there is a next element. if (iterator.hasnext()) iterator.next(); You traverse all elements in a linked list of strings with the following loop: while (iterator. hasnext()) { String name = iterator.next(); Do something with name If your loop simply visits all elements of the linked list, you can use the for each loop: for (String name : employeenames) { Do something with name The add method adds an object after the iterator, then moves the iterator position past the new element. iterator.add("juliet"); The remove method removes the object that was returned by the last call to next or previous, but you cannot call it immediately after a call to add.

24 Output Dick Harry Juliet Nina Tom Expected: Dick Harry Juliet Nina Tom Example import java.util.linkedlist; import java.util.listiterator; /** A program that tests the LinkedList class. */ public class ListTester { public static void main(string[] args) { LinkedList<String> staff = new LinkedList<String>(); staff.addlast( Dick ); staff.addlast( Harry ); staff.addlast( Romeo ); staff.addlast( Tom ); ListIterator<String> iterator = staff.listiterator(); // DHRT iterator.next(); // D HRT iterator.next(); // DH RT // Add more elements after second element iterator.add( Juliet ); // DHJ RT iterator.add( Nina ); // DHJN RT iterator.next(); // DHJNR T // Remove last traversed element iterator.remove(); // DHJN T // Print all elements System.out.print(iterator.next() + ); System.out.println(); System. out. println( Expected: Dick Harry Juliet Nina Tom );

25 import java.util.nosuchelementexception; public class LinkedList { private Node first; private class Node { public Object data; public Node next; public LinkedList() { first = null; public ListIterator listiterator() { return new LinkedListIterator(); private class LinkedListIterator implements ListIterator { private Node position, previous; public LinkedListIterator(){ position = null; previous = null; public Object next(){ if (!hasnext()) throw new NoSuchElementException(); previous = position; // Remember for remove if (position == null) position = first; else position = position.next; return position.data; public boolean hasnext() { if (position == null) return first! = null; else return position.next! = null;... public Object getfirst() { if (first == null) throw new NoSuchElementException(); return first.data; public void addfirst(object element){ Node newnode = new Node(); // 1 newnode.data = element; // 2 newnode.next = first; // 3 first = newnode; // 4 public Object removefirst() { if (first == null) throw new NoSuchElementException(); Object element = first.data; // 1 first = first.next; // 2 return element; // 3... Adding a Node to the Head of a Linked List A Concrete View of a Linked List Implementing Linked Lists (I) Removing the first node from a Linked List

26 Implementing Linked Lists (II) Removing a Node from the Middle of a Linked List with ListIterator Adding a Node to the Middle of a Linked List with ListIterator

27 Sets The Set<T> interface has the same methods of its super-interface Collection<T>. A set is an unordered collection of distinct elements. Elements can be added, located, and removed. Sets don't have duplicates. Adding a duplicate of an element that is already present is silently ignored. There are two different data structures for this purpose, called hash tables and trees. The HashSet and TreeSet classes both implement the Set interface. Set<String> names = new HashSet<String>(); names.add("romeo"); names.add("juliet"); names.remove( Romeo"); if(names.contains( Juliet )... We can use the next and hasnext methods to step through the set: Iterator<String> iter = names.iterator(); while (iter.hasnext()){ String name = iter.next(); Do something with name Warning. A set iterator does not visit the elements in the order in which you inserted them. The set implementation rearranges the elements so that it can locate them quickly. We can also use the for each loop to step through the set : while (String name : names){ Do something with name

28 Set 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( Verificato un duplicato: "+args[i]); System.out.println(s.size()+" distinct words identified: "+s); import java.util.*; public class FindDups2 { public static void main(string args[]) { Set uniques = new HashSet(); Set dups = new HashSet(); for (int i=0; i<args.length; i++) if (!uniques.add(args[i])) dups.add(args[i]); uniques.removeall(dups); // Destructive set-difference System.out.println("Unique words: " + uniques); System.out.println("Duplicate words: " + dups); >java FindDups2 i came i saw i left Unique words: [came, left, saw] Duplicate words: [i] 28

29 Implementing the Set interface HashSet = concrete class that represents a set where objects belong to a hashtable. HashSet should be used when the number of objects in Set is low. The objects in a collection Set should rewrite the method hashcode() of Object. int h = x.hashcode(); A hash function is a function that computes an integer value, the hash code, from an object, in such a way that different objects are likely to yield different hash codes. A good hash function minimizes collisions identical hash codes for different objects. Hash table Object F Hash code bucket HashSet TreeSet Hash function TreeSet = concrete class that represents an ordered set supported by a red-black tree (an always balanced tree). We can extract ordered sequences that implement Set. The objects we add to a TreeSet must be compatible with ordering. TreeSet haa a constructor that allows to add to the Set object a criterium of comparison between two objects: TreeSet ord = new TreeSet(); ord.add( Claude ); ord.add( Mary ); ord.add( Peter ); Iterator it = ord.iterator(); while (it.hasnext()) System.out.println(it.next()); 29

30 HashSet Example import java.util.*; public class hs { static HashSet hs = new HashSet(); public static void main(string[] arg) { createhs(); showhs(); System.out.println( There are "+hs.size() +" divisions"); public static void createhs() { String s1= Sistems", s2= Data", s3= Marketing"; hs.add( s1 ); hs.add( s2 ); hs.add( s3 ); Output: public static void showhs() { Iterator i = hs.iterator(); while( i.hasnext() ) { System.out.println(" Division: "+ i.next() ); Output if the collection was an TreeSet: java hs Division: Data Division: Marketing Division: Sistems There are 3 divisions java hs Division: Marketing Division: Sistems Division: Data There are 3 divisions

31 import java.util.hashset; import java.util.scanner; import java.util.set; public class SetDemo { public static void main(string[] args) { Set<String> names = new HashSet<String>(); Scanner in = new Scanner(System.in); boolean done = false; while (!done) { System.out.print( Add name, Q when done: ); String input = in.next(); if (input.equalsignorecase( Q )) done = true; else { names.add(input); print(names); done = false; while (!done) { System.out.print( Remove name, Q when done: ); String input = in.next(); if (input.equalsignorecase( Q )) done = true; else { names.remove(input); print(names); private static void print(set<string> s) { System.out.print( { ); for (String element : s) { System.out.print(element); System.out.print( ); System.out.println( ); Example with HashSet Output Add name, Q when done: Dick { Dick Add name, Q when done: Tom { Tom Dick Add name, Q when done: Harry { Harry Tom Dick Add name, Q when done: Tom { Harry Tom Dick Add name, Q when done: Q Remove name, Q when done: Tom { Harry Dick Remove name, Q when done: Jerry { Harry Dick Remove name, Q when done: Q

32 A Hash Table with Buckets to Store Elements with the Same Hash Code

33 TreeSet The object added to a TreeSet should implement the Comparable interface. The objects will be added in a tree in ascendent order. import java.util.*; public class SetExample { public static void main(string args[]) { Set set = new TreeSet(); set.add("clara"); set.add( Gene"); set.add("bernadine"); set.add("elizabeth"); set.add("gene"); System.out.println(set); Bernardine Clara Gene Elizabeth For efficiency, objects added to a HashSet need to implement the hashcode() method in a manner that properly distributes the hash codes. import java.util.*; public class SetExample { public static void main(string args[]) { Set set = new HashSet(); set.add("clara"); set.add( Gene"); set.add("bernadine"); set.add("elizabeth"); set.add("gene"); System.out.println(set); Set sortedset = new TreeSet(set); System.out.println(sortedSet);

34 To sort a collection of coins, the Coin class would need to implement this interface and define a compareto method: public class Coin implements Comparable {... public int compareto(object otherobject){ Coin other = (Coin) otherobject; if (value < other.value) return -1; if (value == other.value) return 0; return 1;... When you implement the compareto method of the Comparable Sorting interface, Coins you must make sure that the method defines a total relationship, with the following three properties: Antisymmetric: if a.compareto(b) 0, then b.compareto(a) 0 Reflexive: a.compareto(a) = 0 Transitive: if a.compareto(b) 0 and b.compareto(c) 0, then a.compareto(c) 0 Once your Coin class implements the Comparable interface, you can simply pass an array of coins to the Arrays.sort method: // Add coins... Arrays.sort(coins); If the coins are stored in an ArrayList, use the Collections.sort method instead; it uses the merge sort algorithm: ArrayList<Coin> coins = new ArrayList<Coin>(); // Add coins... Collections. sort (coins);

An Introduction to Data Structures

An Introduction to Data Structures An Introduction to Data Structures Advanced Programming ICOM 4015 Lecture 17 Reading: Java Concepts Chapter 20 Fall 2006 Adapded from Java Concepts Companion Slides 1 Chapter Goals To learn how to use

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

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. 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

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

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

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

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

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 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 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

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

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

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

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

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

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

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

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

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

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

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

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

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

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

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

엄현상 (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

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

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

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

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

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

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

3/20/2015. Chapter 19 Sorting and Searching SELECTION SORT INSERTION SORT MERGE SORT THE QUICKSORT ALGORITHM MERGE SORT VS SELECTION SORT

3/20/2015. Chapter 19 Sorting and Searching SELECTION SORT INSERTION SORT MERGE SORT THE QUICKSORT ALGORITHM MERGE SORT VS SELECTION SORT Chapter 19 Sorting and Searching The Plan For Today APCS Account Chapter 18 Assignment Towers of Hanoi Chapter 19 19.6: Searching 19.7: Binary Search 19.8: Sorting Real Data Ch18/19 Work Time SELECTION

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

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

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

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

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework SUMMARY COLLECTIONS FRAMEWORK PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 Introduction Collections and

More information

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

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,

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

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

generic programming alberto ferrari university of parma

generic programming alberto ferrari university of parma generic programming alberto ferrari university of parma contents generic programming java generic programming methods & generic programming classes & generic programming java with generics generic methods

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

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

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

Java Review: Objects

Java Review: Objects Outline Java review Abstract Data Types (ADTs) Interfaces Class Hierarchy, Abstract Classes, Inheritance Invariants Lists ArrayList LinkedList runtime analysis Iterators Java references 1 Exam Preparation

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

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

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net Sorting Tree Balancing A sorted tree is balanced iff for each node holds: Math.abs(size(node.left)

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

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

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

Principles of Software Construction: Objects, Design and Concurrency. More design patterns and Java Collections. toad Principles of Software Construction: Objects, Design and Concurrency 15-214 toad More design patterns and Java Collections Spring 2013 Christian Kästner Charlie Garrod School of Computer Science 2012-13

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

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

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net MULTIVARIATE TREES 2 Multivariate Trees general class of trees nodes can have any number of children

More information

Collections. OOP encapsulates data inside classes, but this doesn t make how you

Collections. OOP encapsulates data inside classes, but this doesn t make how you 2 Collections COLLECTION INTERFACES CONCRETE COLLECTIONS THE COLLECTIONS FRAMEWORK ALGORITHMS LEGACY COLLECTIONS OOP encapsulates data inside classes, but this doesn t make how you organize the data inside

More information

Class 26: Linked Lists

Class 26: Linked Lists Introduction to Computation and Problem Solving Class 26: Linked Lists Prof. Steven R. Lerman and Dr. V. Judson Harward 2 The Java Collection Classes The java.util package contains implementations of many

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

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

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

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

Section Lists and Sets

Section Lists and Sets Section 10.2 Lists and Sets IN THE PREVIOUS SECTION, we looked at the general properties of collection classes in Java. In this section, we look at some specific collection classes and how to use them.

More information

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology Lists and Iterators CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology Announcements Should be making progress on VectorGraphics. Should have turned in CRC cards,

More information

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Collections by Vlad Costel Ungureanu for Learn Stuff Collections 2 Collections Operations Add objects to the collection Remove objects from the collection Find out if an object (or group of objects) is

More information

Advanced Data Structures

Advanced Data Structures Chapter 16 Advanced Data Structures CHAPTER GOALS To learn about the set and map data types To understand the implementation of hash tables To be able to program hash functions To learn about binary trees

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

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

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

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc. Contents Topic 08 - Collections I. Introduction - Java Collection Hierarchy II. Choosing/using collections III. Collection and Iterator IV. Methods of Collection V. Concrete classes VI. Implementation

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

Advanced Programming Generics Collections

Advanced Programming Generics Collections Advanced Programming Generics Collections The Context Create a data structure that stores elements: a stack, a linked list, a vector a graph, a tree, etc. What data type to use for representing the elements

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

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

CS 307 Final Spring 2008

CS 307 Final Spring 2008 Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2008 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to

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

Collections. James Brucker

Collections. James Brucker Collections James Brucker Collection A Collection is a group of objects. Set an unordered collection no duplicates List ordered collection duplicates are allowed can add or remove elements anywhere in

More information

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

Software 1 with Java. Recitation No. 6 (Collections) Software 1 with Java Recitation No. 6 (Collections) Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2

More information

Generics method and class definitions which involve type parameters.

Generics method and class definitions which involve type parameters. Contents Topic 07 - Generic Programming I. Introduction Example 1 User defined Generic Method: printtwice(t x) Example 2 User defined Generic Class: Pair Example 3 using java.util.arraylist II. Type

More information

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

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 Answers 1) B 2) C 3) A 4) D 5) Non-static members 6) Static members 7) Default 8) abstract 9) Local variables 10) Data type default value 11) Data type default value 12) No 13) No 14) Yes 15) No 16) No

More information

Lists using LinkedList

Lists using LinkedList Lists using LinkedList 1 LinkedList Apart from arrays and array lists, Java provides another class for handling lists, namely LinkedList. An instance of LinkedList is called a linked list. The constructors

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

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

Introduction to Programming Using Java (98-388)

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

More information

Objects and Iterators

Objects and Iterators Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a

More information

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

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References Reading Readings and References Class Libraries CSE 142, Summer 2002 Computer Programming 1 Other References» The Java tutorial» http://java.sun.com/docs/books/tutorial/ http://www.cs.washington.edu/education/courses/142/02su/

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

Introducing Generics

Introducing Generics Generics Introducing Generics Generics allow reference types (classes, interfaces, and array types) and methods to be parameterized with type information. An abstract data type (ADT) defines both the types

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

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

Doubly LinkedList is Symmetrical! LinkedList Efficiency. Monday, April 8, 13. insert insert remove remove remove walk

Doubly LinkedList is Symmetrical! LinkedList Efficiency. Monday, April 8, 13. insert insert remove remove remove walk How Can We Improve the State of Experimental Evaluation in Computer Siene Peter Sweeney IBM Researh, TJ Watson Friday, April 12, 12:00 Kendade 307 1 Doubly LinkedList is Symmetrial! insert insert remove

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

CS Programming Language Java. Fall 2004 Sept. 29

CS Programming Language Java. Fall 2004 Sept. 29 CS3101-3 Programming Language Java Fall 2004 Sept. 29 Road Map today Java review Homework review Exception revisited Containers I/O What is Java A programming language A virtual machine JVM A runtime environment

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

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 reloaded

Java Collections Framework reloaded Java Collections Framework reloaded October 1, 2004 Java Collections - 2004-10-01 p. 1/23 Outline Interfaces Implementations Ordering Java 1.5 Java Collections - 2004-10-01 p. 2/23 Components Interfaces:

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

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

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

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

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

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know Organizing Data Data Structures that we know 17 Java Collections Generic Types, Iterators, Java Collections, Iterators Today: Arrays Fixed-size sequences Strings Sequences of characters Linked Lists (up

More information