62
Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 1 C hapter11 How to w ork w ith collections and generics

Murach’s Beg. Java 2, JDK 5, C11© 2005, Mike Murach & Associates, Inc.Slide 1

  • View
    219

  • Download
    0

Embed Size (px)

Citation preview

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 1

Chapter 11

How to work with collections and generics

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 2

Objectives

Applied

Given a list of values or objects, write code that creates an array list or linked list to store the values or objects. Then, write code that uses the values or objects in the list.

Given a list of key-value pairs, write code that creates a hash map or tree map to store the entries. Then, write code that uses the entries in the list.

Given Java code that uses any of the language elements presented in this chapter, explain what each statement does.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 3

Objectives (continued)

Knowledge

Describe the similarities and differences between arrays and collections.

Name the two main types of collections defined by the collection framework and explain how they differ.

Describe the generics feature and explain how you use it to create typed collections and classes.

Explain what an array list is and, in general, how it works.

Explain what autoboxing is.

Explain what a linked list is and, in general, how it works

Explain how you would decide whether to use an array list or a linked list for a given application.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 4

Objectives (continued) Explain what a queue is and describe the two basic operations that a

queue provides.

Describe the main difference between a hash map and a tree map.

Explain what an untyped collection is and what you must do to work with one.

Explain what the legacy collections are.

Explain when you need to use a wrapper class with untyped collections.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 5

How arrays and collections are similar Like an array, a collection is an object that can store multiple

occurrences of other objects.

Some collection types (such as ArrayList) use arrays internally to store data.

How arrays and collections differ An array is a Java language feature. Collections are classes in the

Java API.

Collection classes have methods that perform operations that arrays don’t provide.

Arrays are fixed in size. Collections are variable in size.

Arrays can store primitive types. Collections can’t.

Indexes are almost always required to process arrays. Collections are usually processed without using indexes.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 6

Code that uses an array String[] codes = new String[3]; codes[0] = "mcb2"; codes[1] = "java"; codes[2] = "jsps"; for (int i = 0; i < codes.length; i++) System.out.println(codes[i]);

Code that uses a collection ArrayList<String> codes = new ArrayList<String>(); codes.add("mcb2"); codes.add("java"); codes.add("jsps"); for (String s : codes) System.out.println(s);

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 7

The collection framework

Collection

Set List

HashSet ArrayList LinkedList

Map

HashMap TreeMap

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 8

The Java collection framework and classes The Java collection framework is interface based. That means that

each class in the collection implements one of the interfaces defined by the collection framework.

The collection framework consists of two class hierarchies: Collection and Map.

Collections store individual objects as elements. Maps store pairs of key objects and value objects in a way that lets you retrieve a value object based on its key.

Although there are many classes in the Java collection framework, the most commonly used classes are the ArrayList, LinkedList, HashSet, HashMap, and TreeMap classes.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 9

Collection interfaces

Interface Description

Collection Defines the basic methods available for all collections.

Set Defines a type of collection in which no duplicate elements are allowed.

List Defines a type of collection that maintains the order in which elements were added to the list.

Map Defines a map, which holds one or more key-value pairs, each consisting of: (1) a key that uniquely identifies an entry and (2) a value that provides data for that key.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 10

Common collection classes

Class Description

ArrayList Works much like an array, but can be easily expanded to accommodate new elements. Very efficient for accessing elements in random sequence, but inserting elements into the middle of the list can be inefficient.

LinkedList Similar to an array list, but with more features. Less efficient than an array list for random access, but more efficient when inserting items into the middle of the list.

HashSet A collection that stores a set of unique values based on a hash code. Duplicates are not allowed. Objects you add to a hash set must implement a method called hashCode to generate a hash code for the object, which is used to ensure uniqueness.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 11

Common collection classes (continued)

Class Description

HashMap Similar to a hash set, but is based on the Map interface rather than the Set interface. As a result, a hash map stores key-value pairs whose keys must be unique.

TreeMap Stores key-value pairs in a special arrangement called a tree. Entries are automatically maintained in key sequence.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 12

The syntax for specifying the type of elements in a collection

CollectionClass<Type> collectionName = new CollectionClass<Type>();

A statement that creates an array list of type String

ArrayList<String> codes = new ArrayList<String>();

A statement that creates an array list of integers ArrayList<Integer> numbers = new ArrayList<Integer>();

Code that creates a linked list of type Product LinkedList<Product> products; products = new LinkedList<Product>();

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 13

The syntax for declaring a class that uses generic types

public class ClassName<TypeVariable [,TypeVariable]...>{}

A class statement for a class that implements a queue

public class GenericQueue<E>{}

An introduction to generics Generics refers to a new feature of Java 5.0 that lets you create

typed collections.

A typed collection can hold only objects of a certain type.

To declare a variable that refers to a typed collection, list the type in angle brackets (<>) following the name of the collection class.

When you use a constructor for a typed collection, you specify the type variable in angle brackets following the constructor name.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 14

An introduction to generics (continued) The type variable can’t be a primitive type such as int or double.

However, it can be a wrapper class or a user-defined class.

If you do not specify a type for a collection, the collection can hold any type of object. However, the Java compiler will issue warning messages whenever you access the collection to warn you that type checking can’t be performed for the collection.

To create a generic class that lets you specify type information, specify one or more type variables in angle brackets following the class name on the class statement.

Then, you can use the type variable within the class anywhere you would normally specify a type.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 15

The ArrayList class java.util.ArrayList

An introduction to array lists An array list is a collection that’s similar to an array, but can

change its capacity as elements are added or removed.

The ArrayList class uses an array to store the elements it contains.

You can specify the type of elements to be stored in the array list by naming a type in angle brackets.

You can specify the size of an array list when you create it, or you can let the array list default to an initial capacity of 10 elements.

The capacity of an array list automatically increases whenever necessary.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 16

Constructors of the ArrayList class

Constructor Description

ArrayList<E>() Creates an empty array list with an initial capacity of ten objects of the specified type.

ArrayList<E>(intCapacity) Creates an empty array list with the specified capacity.

ArrayList<E>(Collection) Creates an array list containing the elements of the specified collection.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 17

Common methods of the ArrayList class

Method Description

add(object) Adds the specified object to the end of the list.

add(index, object) Adds the specified object at the specified index position.

clear() Removes all elements from the list.

contains(object) Returns true if the specified object is in the list.

get(index) Returns the object at the specified index position.

indexOf(object) Returns the index position of the specified object.

isEmpty() Returns true if the list is empty.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 18

Common methods of the ArrayList class (continued)

Method Description

remove(index) Removes the object at the specified index position.

remove(object) Removes the specified object.

set(index, object) Sets the element at the specified index to the specified object.

size() Returns the number of elements in the list.

toArray() Returns an array containing the elements of the list.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 19

Code that uses an array list of type String // create an array list of type String ArrayList<String> codes = new ArrayList<String>(); // add three strings codes.add("mbdk"); codes.add("citr"); codes.add(0, "warp"); // print the array list for (int i =0; i < codes.size(); i++) { String code = codes.get(i); System.out.println(code); }

Resulting output warp mbdk citr

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 20

Another way to display the contents of a collection

System.out.println(codes);

Resulting output [warp, mbdk, citr]

Code that replaces and deletes objects codes.set(1,"wuth"); codes.remove("warp"); codes.remove(1); System.out.print(codes);

Resulting output [wuth]

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 21

Code that uses an array list of type Integer ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println(numbers);

Resulting output [1, 2, 3]

Note When you use generics to create a collection that holds a wrapper

type, the compiler automatically converts the primitive type to its wrapper type and vice versa using a technique called autoboxing.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 22

Console output for the Invoice application Welcome to the invoice application. Enter product code: java Enter quantity: 1 Another line item? (y/n): y Enter product code: jsps Enter quantity: 2 Another line item? (y/n): n Code Description Price Qty Total ---- ----------- ----- --- ----- java Murach's Beginning Java 2 $49.50 1 $49.50 jsps Murach's Java Servlets and JSP $49.50 2 $99.00 Invoice total: $148.50

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 23

Classes used by the Invoice application

Name Description

Product Represents a Product object.

ProductDB Provides a getProduct method that retrieves the Product object for a specified product code.

Validator Provides methods that accept and validate user input.

LineItem Represents an invoice line item, which includes a Product object, a quantity, and a total.

Invoice Represents a single invoice. The line items are represented by an array list.

InvoiceApp Contains the main method for the Invoice application.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 24

The constructor and methods for the Invoice class

Constructor Description Invoice() Creates an empty invoice.

Method Description void addItem(LineItem lineItem)

Adds the specified line item to the invoice.

ArrayList getLineItems() Returns an ArrayList object that contains the line items for the invoice.

double getInvoiceTotal() Returns a double that contains the sum of the totals for the line items in the invoice.

String getFormattedTotal() Returns a String that contains the invoice total formatted as currency.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 25

The code for the Invoice class import java.text.NumberFormat; import java.util.ArrayList; public class Invoice { // the instance variable private ArrayList<LineItem> lineItems; // the constructor public Invoice() { lineItems = new ArrayList<LineItem>(); } // a method that adds a line item public void addItem(LineItem lineItem) { this.lineItems.add(lineItem); }

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 26

The code for the Invoice class (continued) // the get accessor for the line item collection public ArrayList<LineItem> getLineItems() { return lineItems; } // a method that gets the invoice total public double getInvoiceTotal() { double invoiceTotal = 0; for (LineItem lineItem : this.lineItems) { invoiceTotal += lineItem.getTotal(); } return invoiceTotal; } // a method that returns the invoice total in currency format public String getFormattedTotal() { NumberFormat currency = NumberFormat.getCurrencyInstance(); return currency.format(this.getInvoiceTotal()); } }

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 27

The code for the InvoiceApp class import java.util.Scanner; public class InvoiceApp { public static Invoice invoice = new Invoice(); public static void main(String args[]) { System.out.println("Welcome to the invoice application.\n"); getLineItems(); displayInvoice(); } public static void getLineItems() { Scanner sc = new Scanner(System.in); String choice = "y"; while (choice.equalsIgnoreCase("y")) { // get the input from the user String productCode = Validator.getString(sc, "Enter product code: "); int quantity = Validator.getInt(sc, "Enter quantity: ", 0, 1000);

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 28

The code for the InvoiceApp class (continued) Product product = ProductDB.getProduct(productCode); invoice.addItem(new LineItem(product, quantity)); // see if the user wants to continue choice = Validator.getString(sc, "Another line item? (y/n): "); System.out.println(); } } public static void displayInvoice() { System.out.println( "Code\tDescription\t\t\tPrice\tQty\tTotal"); System.out.println( "----\t-----------\t\t\t-----\t---\t-----");

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 29

The code for the InvoiceApp class (continued) for (LineItem lineItem : invoice.getLineItems()) { Product product = lineItem.getProduct(); String s = product.getCode() + "\t" + product.getDescription() + "\t" + product.getFormattedPrice() + "\t" + lineItem.getQuantity() + "\t" + lineItem.getFormattedTotal(); System.out.println(s); } System.out.println("\n\t\t\t\t\tInvoice total:\t" + invoice.getFormattedTotal() + "\n"); } }

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 30

The LinkedList class java.util.LinkedList

A constructor for the LinkedList class

Constructor Description

LinkedList<E>() Creates an empty linked list using the specified type.

An introduction to linked lists A linked list is a collection that’s similar to an array list, but it

doesn’t use an array to store its elements. Instead, each element contains pointers that are used to refer to adjacent elements.

You can specify the type of elements the linked list can contain by listing the type in angle brackets.

The LinkedList class contains methods that let you perform more advanced operations than the ArrayList class.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 31

Common methods of the LinkedList class

Method Description

add(object) Adds the specified object to the list.

add(index, object) Adds the specified object at the specified index position.

addFirst(object) Adds the specified object to the beginning of the list.

addLast(object) Adds the specified object to the end of the list.

clear() Removes all elements from the list.

contains(object) Returns true if the specified object is in the list.

get(index) Returns the object at the specified index position.

getFirst() Returns the first element in the list.

getLast() Returns the last element in the list.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 32

Common methods of the LinkedList class (continued)

Method Description

indexOf(object) Returns the index position of the specified object.

peek() Returns but doesn’t remove the first element in the list.

offer(object) Attempts to add the specified object to the end of the list. Returns true if the object was added. Returns false if the object is rejected.

poll() Returns and removes the first element from the list. Returns null if the list is empty.

remove() Returns and removes the first element from the list. Throws NoSuchElementException if the list is empty.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 33

Common methods of the LinkedList class (continued)

Method Description

remove(index) Removes and returns the object at the specified index position.

remove(object) Removes the specified object.

removeFirst() Removes and returns the first element of the list.

removeLast() Removes and returns the last element of the list.

set(index, object) Replaces the element at the specified index position with the specified object.

size() Returns the number of elements in the list.

toArray() Returns an array containing the elements of the list.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 34

Code that creates a linked list of type String // create a linked list of type String LinkedList<String> codes = new LinkedList<String>(); // add three strings codes.add("mbdk"); codes.add("citr"); codes.add(0, "warp"); System.out.println(codes);

Resulting output [warp, mbdk, citr]

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 35

Code that adds elements to the beginning and end of the linked list

codes.addFirst("wuth"); codes.addLast("wooz"); System.out.println(codes);

Resulting output [wuth, warp, mbdk, citr, wooz]

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 36

Code that uses an enhanced for loop to process the linked list

for (String s : codes) System.out.println(s);

Resulting output wuth warp mbdk citr wooz

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 37

Code that retrieves the first and last elements of the linked list

String firstString = codes.removeFirst(); String lastString = codes.removeLast(); System.out.println(firstString); System.out.println(lastString); System.out.println(codes);

Resulting output wuth wooz [warp, mbdk, citr]

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 38

Using a linked list to implement a generic queue A queue is a first-in, first-out collection. To implement a queue,

you can use a linked list.

A class that implements a queue is typically declared with a type variable that’s used to specify the type of objects the queue will hold.

Basic methods of a class that implements a generic queue

Method Description

push(element) Adds the specified element to the end of the queue.

pull() Retrieves and removes an element from the front of the queue.

size() Returns the number of elements in the queue.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 39

A GenericQueue class that implements a queue import java.util.LinkedList; public class GenericQueue<E> { private LinkedList<E> list = new LinkedList<E>(); public void push(E item) { list.addLast(item); } public E pull() { return list.removeFirst(); } public int size() { return list.size(); } }

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 40

Code that uses the GenericQueue class GenericQueue<String> q1 = new GenericQueue<String>(); q1.push("Item One"); q1.push("Item Two"); q1.push("Item Three"); System.out.println("The queue contains " + q1.size() + " items"); while (q1.size > 0) System.out.println(ql.pull()); System.out.println("The queue now contains " + ql.size() + " items");

Resulting output The queue contains 3 items Item One Item Two Item Three The queue now contains 0 items

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 41

Console output for the enhanced Invoice application Welcome to the invoice application. Enter line items for invoice 1 Enter product code: java Enter quantity: 1 Another line item? (y/n): n Another invoice? (y/n): y Enter line items for invoice 2 Enter product code: jsps Enter quantity: 2 Another line item? (y/n): n Another invoice? (y/n): n

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 42

Console output for the enhanced Invoice application (continued) You entered the following invoices: Number Total ------ ----- 1 $49.50 2 $99.00 Total for all invoices: $148.50

Note In this version of the Invoice application, the user can enter

multiple invoices that are then stored in a queue created from the GenericQueue class.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 43

Code for the InvoiceApp class import java.util.Scanner; import java.text.NumberFormat; public class InvoiceApp { private static GenericQueue<Invoice> invoices = new GenericQueue<Invoice>(); private static Invoice invoice; private static Scanner sc; public static void main(String args[]) { System.out.println("Welcome to the Invoice application.\n"); getInvoices(); displayInvoices(); }

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 44

Code for the InvoiceApp class (continued) public static void getInvoices() { sc = new Scanner(System.in); int invoiceNumber = 1; String anotherInvoice = "y"; while (anotherInvoice.equalsIgnoreCase("y")) { invoice = new Invoice(); System.out.println("\nEnter line items for invoice " + invoiceNumber); getLineItems(); invoices.push(invoice); // see if the user wants to continue anotherInvoice = Validator.getString(sc, "Another invoice? (y/n): "); System.out.println(); invoiceNumber++; } }

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 45

Code for the InvoiceApp class (continued) public static void getLineItems() { String anotherItem = "y"; while (anotherItem.equalsIgnoreCase("y")) { // get the input from the user String productCode = Validator.getString(sc, "Enter product code: "); int quantity = Validator.getInt(sc, "Enter quantity: ", 0, 1000); Product product = ProductDB.getProduct(productCode); invoice.addItem(new LineItem(product, quantity)); // see if the user wants to continue anotherItem = Validator.getString(sc, "Another line item? (y/n): "); System.out.println(); } }

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 46

Code for the InvoiceApp class (continued) public static void displayInvoices() { System.out.println("You entered the following invoices:\n"); System.out.println("Number\tTotal"); System.out.println("------\t-----"); double batchTotal = 0; int invoiceNumber = 1; while (invoices.size() > 0) { Invoice invoice = invoices.pull(); System.out.println(invoiceNumber + "\t" + invoice.getFormattedTotal()); invoiceNumber++; batchTotal += invoice.getInvoiceTotal(); } NumberFormat currency = NumberFormat.getCurrencyInstance(); System.out.println("Total for all invoices: " + currency.format(batchTotal)); } }

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 47

The HashMap and TreeMap classes java.util.HashMap java.util.TreeMap

An introduction to maps A map is a collection that contains values that are associated with

keys.

The main difference between a hash map and a tree map is that a tree map automatically maintains entries in order based on the key values.

If an application doesn’t require that the entries be kept in order, a hash map is often more efficient than a tree map.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 48

Common constructors of the HashMap and TreeMap classes

Constructor Description

HashMap<K,V>() Creates an empty HashMap using the specified types for the keys and values.

TreeMap<K,V>() Creates an empty TreeMap using the specified types for the keys and values.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 49

Common methods of the HashMap and TreeMap classes

Method Description

clear() Removes all entries from the map.

containsKey(key) Returns true if the specified key is in the map.

containsValue(value) Returns true if the specified value is in the map.

entrySet() Returns a set of all the entries in the map as Map.Entry objects.

get(key) Returns the value for the entry with the specified key. Returns null if the key isn’t found.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 50

Common methods of the HashMap and TreeMap classes (continued)

Method Description

put(key, value) Adds an entry with the specified key and value, or replaces the value if an entry with the key already exists.

remove(key) Removes the entry with the specified key.

size() Returns the number of entries in the map.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 51

Common methods of the Map.Entry interface

Method Description

getKey() Returns the key for the map entry.

getValue() Returns the value for the map entry.

Note Each entry of a map implements the Map.Entry interface in the

java.util.Map package. You can use two of the Map.Entry methods to get the key and value for an entry.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 52

Code that uses a hash map // create an empty hash map HashMap<String, String> books = new HashMap<String, String>(); // add three entries books.put("wooz", "Wizard of Oz"); books.put("mbdk", "Moby Dick"); books.put("wuth", "Wuthering Heights"); // print the entries for (Map.Entry book : books.entrySet()) System.out.println(book.getKey() + ": " + book.getValue()); // print the entry whose key is "mbdk" System.out.println("\nCode mbdk is " + books.get("mbdk"));

Resulting output wuth: Wuthering Heights mbdk: Moby Dick wooz: Wizard of Oz Code mbdk is Moby Dick

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 53

Code that uses a tree map // create an empty tree map TreeMap<String,String> books = new TreeMap<String, String>(); // add three entries books.put("wooz", "Wizard of Oz"); books.put("mbdk", "Moby Dick"); books.put("wuth", "Wuthering Heights"); // print the entries for (Map.Entry book : books.entrySet()) System.out.println(book.getKey() + ": " + book.getValue()); // print the entry whose key is "mbdk" System.out.println("\nCode mbdk is " + books.get("mbdk"));

Resulting output mbdk: Moby Dick wooz: Wizard of Oz wuth: Wuthering Heights Code mbdk is Moby Dick

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 54

Legacy collection classes

Class Description

Vector Provides features similar to the more powerful ArrayList class.

HashTable Provides features similar to the more powerful HashMap class.

Stack A type of Vector that implements a stack, which is a last-in, first-out list. The LinkedList class is now the preferred class for implementing a stack.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 55

An introduction to legacy collection classes The collection hierarchy was introduced with Java 1.2.

For compatibility reasons, Java still supports older collection classes such as Vector, HashTable, and Stack. However, you should avoid using these classes for new software development.

The Vector, HashTable, and Stack classes aren’t deprecated. They are still fully supported as part of the Java API.

The Vector class was the most commonly used legacy collection class. The newer ArrayList class is an improved version of the Vector class, so the code used to work with a vector is similar to the code used to work with an array list.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 56

Code that uses a vector // create a vector Vector codes = new Vector(); // add three strings codes.add("mbdk"); codes.add("citr"); codes.add(0, "warp"); // print the vector for (int i =0; i < codes.size(); i++) { String code = (String)codes.get(i); System.out.println(code); }

Resulting output warp mbdk citr

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 57

How to use an untyped collection Code written before Java 5.0 uses untyped collections, which

don’t use generics to specify the element type.

Untyped collections hold elements of type Object.

No special coding is required to add objects to an untyped collection.

Typically, you must specify a cast to retrieve objects from an untyped collection.

The Java 5.0 compiler generates a warning message whenever you add an element to an untyped collection.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 58

Code that stores strings in an untyped array list // create an untyped array list ArrayList products = new ArrayList(); // add three productss products.add(new Product("dctp", "Duct Tape", 4.95)); products.add(new Product("blwr", "Bailing Wire", 14.95)); products.add(new Product("cgum", "Chewing Gum", 0.95)); // print the array list for (int i = 0; i < products.size(); i++) { Product p = (Product)products.get(i); System.out.println(p.getCode() + "\t" + p.getDescription() + "\t" + p.getFormattedPrice()); }

Resulting output dctp Duct Tape $4.95 blwr Bailing Wire $14.95 cgum Chewing Gum $0.95

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 59

Compiler warnings generated by the code for the untyped array list H:\Java 1.5\examples\ch10\Untyped Arraylist\UntypedArrayList.java:13: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList products.add(new Product("dctp", "Duct Tape", 4.95)); ^ H:\Java 1.5\examples\ch10\Untyped Arraylist\UntypedArrayList.java:14: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList products.add(new Product("blwr", "Bailing Wire", 14.95)); ^ H:\Java 1.5\examples\ch10\Untyped Arraylist\UntypedArrayList.java:15: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList products.add(new Product("cgum", "Chewing Gum", 0.95)); ^ 3 warnings Tool completed successfully

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 60

How to use wrapper classes with untyped collections Because untyped collections can’t hold primitive types, you must

use wrapper classes to store primitive types in them.

To add a primitive type to an untyped collection:

create an instance of the appropriate wrapper class

pass the value you want it to hold to the constructor of that class

You can assign the wrapper type to a primitive type variable without any explicit casting.

To retrieve an element that holds a primitive type, cast the element to the wrapper type.

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 61

Wrapper classes for primitive types

Primitive type Wrapper class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Char

boolean Boolean

Murach’s Beg. Java 2, JDK 5, C11 © 2005, Mike Murach & Associates, Inc. Slide 62

Code that adds integers to an untyped array list ArrayList numbers = new ArrayList(); numbers.add(new Integer(1)); numbers.add(new Integer(2)); numbers.add(new Integer(3));

Code that retrieves integers from the array list for (int i = 0; i < numbers.size(); i++) { int number = (Integer)numbers.get(i); System.out.println(number); }

Resulting output 1 2 3