100% found this document useful (1 vote)
107 views

Building Java Programs: Chapter 10, 11 Lecture 22: 143 Preview

This document discusses problems with using arrays and how array lists and hash maps can provide solutions. It covers array list and hash map declarations and common methods. Examples are provided for mapping state strings to colors using these data structures.

Uploaded by

chrkiitm
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
107 views

Building Java Programs: Chapter 10, 11 Lecture 22: 143 Preview

This document discusses problems with using arrays and how array lists and hash maps can provide solutions. It covers array list and hash map declarations and common methods. Examples are provided for mapping state strings to colors using these data structures.

Uploaded by

chrkiitm
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 19

Building Java Programs

Chapter 10, 11 Lecture 22: 143 Preview


optional reading: 10.1, 11.1 - 11.3

Copyright 2010 by Pearson Education

Copyright 2010 by Pearson Education

Problems with arrays


We need to know the size when we declare an array, and

we cant change it later

Cant add more elements


Cant shrink the array to avoid wasting space

Could get around this with Arrays.copyOf

No method to find the index of a given object in an array Could use Arrays.sort and Arrays.binarySearch, but this could be inefficient No method to add/remove from the middle of the list

without overwriting a given element

Wed have to write our own methods


3

Copyright 2010 by Pearson Education

Problems with arrays


We need to know the size when we declare an array, and

we cant change it later

Cant add more elements


Cant shrink the array to avoid wasting space

Could get around this with Arrays.copyOf

No method to find the index of a given object in an array Could use Arrays.sort and Arrays.binarySearch, but this could be inefficient No method to add/remove from the middle of the list

without overwriting a given element

Wed have to write our own methods


4

Copyright 2010 by Pearson Education

ArrayLists
Arrays that dynamically resize themselves to accommodate

adding or removing elements

Copyright 2010 by Pearson Education

ArrayList declaration
Arrays: type[] name = new type[length]; ArrayList: ArrayList<type> name = new ArrayList<type>();

Example:

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


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

ArrayList Methods
Method name add(obj) add(index, obj) contains(obj) Description Adds obj to the end of the list Adds obj at the specified index, shifting higher-index elements to make room Whether the list contains obj

get(i)
indexOf(obj) lastIndexOf(obj) remove(i) remove(obj) set(i, obj) size()
Copyright 2010 by Pearson Education

Get the object at index i


Find the lowest index of obj in the list, -1 if not found Find the highest index of obj in the list, -1 if not found Remove the element at index i Remove the lowest index occurrence of obj Set the element at index i to obj The number of elements in the list
7

Cities revisited
Remember our Cities example?
City Seattle State Population Latitude Longitude WA 616627 47621800 -122350326

There was information about which state each city is in that

we just ignored.

Lets add a legend that shows which states the cities we

plotted were from Why would this have been difficult with standard arrays?
Lets pick a different color for each state, and color all cities in

that state with that color Lets 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

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 ints

(red, green, and blue) We can use the states 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

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<String> called states and

a Graphics object called g

As we encounter each state that well 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
10

Copyright 2010 by Pearson Education

Solution details (cont)


Assume we have an ArrayList<String> 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

11

Problems
For large ArrayLists, 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 ArrayLists, that store Strings and Colors, but wed 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 thats a lot of work (Collections wont be able to sort an ArrayList of an arbitrary type either)

Copyright 2010 by Pearson Education

12

Problems
For large ArrayLists, 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 ArrayLists, that store Strings and Colors, but wed 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 thats a lot of work (Collections wont be able to sort an ArrayList of an arbitrary type either)

Copyright 2010 by Pearson Education

13

HashMaps
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 ints

key value

"foo" 12

"bar" 49

"baz" -2

Copyright 2010 by Pearson Education

14

HashMap declaration
HashMap<key_type, value_type> name = new HashMap<key_type, value_type>();
Example:

HashMap<String, Color> colors = new HashMap<String, Color>();


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


15

Copyright 2010 by Pearson Education

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

size() values()

Copyright 2010 by Pearson Education

16

Cities revisited
Well no longer have to generate a Color from a String We can just associate Strings and Colors 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 isnt. Maintaining

that order takes time.

Copyright 2010 by Pearson Education

17

Solution details
Assume we have a HashMap<String, Color> called colors

and a Graphics object called g

As we encounter each state that well 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

18

Solution details (cont)


Assume we have a HashMap<String, Color> called

colors, a Graphics object called g, and int coordinates x and y

For drawing the legend

for (String state : new TreeSet<String>(colors.keySet())) { g.setColor(colors.get(state)); g.drawString(state, x, y); // update x and y }
This is called a foreach loop. A TreeSet doesnt have

indexes, so we cant get the element at index i


Copyright 2010 by Pearson Education

19

You might also like