Copyright 2010 by Pearson Education Building Java Programs Chapter 10, 11 Lecture 22: 143 Preview optional reading: 10.1, 11.1 - 11.3.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Generics, Lists, Interfaces
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Hashing as a Dictionary Implementation
Appendix I Hashing. Chapter Scope Hashing, conceptually Using hashes to solve problems Hash implementations Java Foundations, 3rd Edition, Lewis/DePasquale/Chase21.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
Introducing Hashing Chapter 21 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 10: ArrayList.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
ARRAYS AND ARRAYLISTS Chapter 7. Array  Sequence of values of the same type  Primitive types  Objects  Create an Array  double[] values = new double[10]
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Chapter 19 Java Data Structures
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
CS Collection and Input/Output Classes CS 3331 Fall 2009.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
(c) University of Washington14-1 CSC 143 Java Collections.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
CSE 143 Lecture 11 Maps Grammars slides created by Alyssa Harding
111 © 2002, Cisco Systems, Inc. All rights reserved.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Collections. The Plan ● Why use collections? ● What collections are available? ● How are the collections different? ● Examples ● Practice.
Building Java Programs Chapter 11 Lecture 11-1: Sets and Maps reading:
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
Copyright 2008 by Pearson Education Building Java Programs ArrayList Reading: 10.1.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Hashing as a Dictionary Implementation Chapter 19.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
CSE 143 Lecture 2 ArrayList reading: 10.1 slides created by Marty Stepp
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Collections Dwight Deugo Nesa Matic
CSE 373: Data Structures and Algorithms Lecture 16: Hashing III 1.
CSE 143 Lecture 11: Sets and Maps reading:
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
Using the Java Collection Libraries COMP 103 # T2
CS313D: Advanced Programming Language
Building Java Programs
Object Oriented Programming in java
The Array is Not Enough.
Presentation transcript:

Copyright 2010 by Pearson Education Building Java Programs Chapter 10, 11 Lecture 22: 143 Preview optional reading: 10.1,

Copyright 2010 by Pearson Education 2

3 Problems with arrays We need to know the size when we declare an array, and we can’t change it later Can’t add more elements Can’t shrink the array to avoid wasting space No method to find the index of a given object in an array No method to add/remove from the middle of the list without overwriting a given element Could get around this with Arrays.copyOf Could use Arrays.sort and Arrays.binarySearch, but this could be inefficient We’d have to write our own methods

Copyright 2010 by Pearson Education 4 Problems with arrays We need to know the size when we declare an array, and we can’t change it later Can’t add more elements Can’t shrink the array to avoid wasting space No method to find the index of a given object in an array No method to add/remove from the middle of the list without overwriting a given element Could get around this with Arrays.copyOf Could use Arrays.sort and Arrays.binarySearch, but this could be inefficient We’d have to write our own methods A Better Solution: ArrayList s

Copyright 2010 by Pearson Education 5 ArrayList s Arrays that dynamically resize themselves to accommodate adding or removing elements

Copyright 2010 by Pearson Education 6 ArrayList declaration Arrays: type[] name = new type[length]; ArrayList: ArrayList name = new ArrayList (); Example: ArrayList words = new ArrayList (); Note – the type must be an object, not a primitive type. You can mostly just use primitive types because of autoboxing and unboxing, but you must declare object types such as Boolean, Integer, Double, Character Need to import java.util.*;

Copyright 2010 by Pearson Education 7 ArrayList Methods Method nameDescription add( obj ) Adds obj to the end of the list add( index, obj ) Adds obj at the specified index, shifting higher-index elements to make room contains( obj ) Whether the list contains obj get( i ) Get the object at index i indexOf( obj ) Find the lowest index of obj in the list, -1 if not found lastIndexOf( obj ) Find the highest index of obj in the list, -1 if not found remove( i ) Remove the element at index i remove( obj ) Remove the lowest index occurrence of obj set( i, obj ) Set the element at index i to obj size() The number of elements in the list

Copyright 2010 by Pearson Education 8 Cities revisited Remember our Cities example? City State Population Latitude Longitude Seattle WA There was information about which state each city is in that we just ignored. Let’s add a legend that shows which states the cities we plotted were from Why would this have been difficult with standard arrays? Let’s pick a different color for each state, and color all cities in that state with that color Let’s add that color to our legend as well How will we convert a state (String) to a color (3 ints)?

Copyright 2010 by Pearson Education 9 String to Color using hashCode() All objects have a method called hashCode that returns a number representing that object The Random object has a constructor Random(seed) The seed determines future random numbers The Color object has a constructor that takes 3 int s (red, green, and blue) We can use the state’s hash code to seed a Random object and then generate the red, green, and blue components of a Color. This guarantees that for a given state, we will always generate the same color, but different states will likely have different colors

Copyright 2010 by Pearson Education 10 Solution details Our method converting String to Color public static Color getColor(String state) { Random r = new Random(state.hashCode()); return new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)); } Assume we have an ArrayList called states and a Graphics object called g As we encounter each state that we’ll plot if (!states.contains(state)) { states.add(state); // keep track of states that we plotted } g.setColor(getColor(state)); // Plot the city, it will be the correct color

Copyright 2010 by Pearson Education 11 Solution details (cont) Assume we have an ArrayList called states, a Graphics object called g, and int coordinates x and y For drawing the legend Collections.sort(states); for (int i = 0; i < states.size(); i++) { String state = states.get(i); g.setColor(getColor(state)); g.drawString(state, x, y); // update x and y }

Copyright 2010 by Pearson Education 12 Problems For large ArrayList s, contains can be inefficient We have to generate the Color from the state What if we wanted to associate an arbitrary Color with each state? We could make parallel ArrayList s, that store String s and Color s, but we’d get thrown off when we sort the states for the legend We could create a new object type with a String and a Color field, but that’s a lot of work ( Collections won’t be able to sort an ArrayList of an arbitrary type either)

Copyright 2010 by Pearson Education 13 Problems For large ArrayList s, contains can be inefficient We have to generate the Color from the state What if we wanted to associate an arbitrary Color with each state? We could make parallel ArrayList s, that store String s and Color s, but we’d get thrown off when we sort the states for the legend We could create a new object type with a String and a Color field, but that’s a lot of work ( Collections won’t be able to sort an ArrayList of an arbitrary type either) A Better Solution: HashMap s

Copyright 2010 by Pearson Education 14 HashMap s A data structure that associates keys and values The keys and values can be arbitrary types, but all the keys must be the same type, and all the values must be the same type. The keys must be unique! Think of it as an array that can be indexed on any type, not just int s key"foo""bar""baz" value1249-2

Copyright 2010 by Pearson Education 15 HashMap declaration HashMap name = new HashMap (); Example: HashMap colors = new HashMap (); Note – the type must be an object, not a primitive type. You can mostly just use primitive types because of autoboxing and unboxing, but you must declare object types such as Boolean, Integer, Double, Character Need to import java.util.*;

Copyright 2010 by Pearson Education 16 HashMap Methods Method nameDescription containsKey( obj ) Whether obj is a key in the map containsValue( obj ) Whether obj is a value in the map get( obj ) Get the value associated with the key obj, null if key is not found keyset() Gets the Set of all the keys in the map put( key, val ) Adds a key/value pairing to the map remove( obj ) Remove the mapping for key obj, and return the value that was associated with it, null if key is not found size() The number of entries in the map values() Gets a Collection of all the values in the map

Copyright 2010 by Pearson Education 17 Cities revisited We’ll no longer have to generate a Color from a String We can just associate String s and Color s and keys as values in the map Without going into detail, for large data sets, adding, removing, and finding entries in a HashMap is faster than adding, removing, and finding elements in an ArrayList ArrayList is an ordered list, while HashMap isn’t. Maintaining that order takes time.

Copyright 2010 by Pearson Education 18 Solution details Assume we have a HashMap called colors and a Graphics object called g As we encounter each state that we’ll plot if (!colors.containsKey(state)) { Random r = new Random(); colors.put(state, new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256))); } g.setColor(colors.get(state)); // Plot the city, it will be the correct color

Copyright 2010 by Pearson Education 19 Solution details (cont) Assume we have a HashMap called colors, a Graphics object called g, and int coordinates x and y For drawing the legend for (String state : new TreeSet (colors.keySet())) { g.setColor(colors.get(state)); g.drawString(state, x, y); // update x and y } This is called a foreach loop. A TreeSet doesn’t have indexes, so we can’t get the element at index i