cs 340 data structures

32
CS 340 DATA STRUCTURES Lecture: Arrays, Collections

Upload: hafwen

Post on 22-Feb-2016

27 views

Category:

Documents


0 download

DESCRIPTION

CS 340 Data Structures. Lecture: Arrays, Collections. Today’s Topics. More on arrays Shallow copies, deep copies, and cloning Sorting & searching in arrays Introduction to containers. Arrays. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS 340 Data Structures

CS 340 DATA STRUCTURESLecture: Arrays, Collections

Page 2: CS 340 Data Structures

Today’s Topics

• More on arrays• Shallow copies, deep copies, and cloning• Sorting & searching in arrays• Introduction to containers

Page 3: CS 340 Data Structures

Arrays• An array is a “first-class object,” unlike a C/C++ array, which is just a bunch of contiguous memory locations.

• As for all objects, the array name is a reference to the actual object.

• This object has space sufficient for • the number of references you specify, if your array holds

objects, or• the number of primitive values you specify, if your array

holds primitive types, • plus space to hold the array length.

Page 4: CS 340 Data Structures

Arrays of Primitives

int[] a = new int[3]; // compiler does initialization

3 0 0 0

a.length a[0] a[1] a[2]

int[] a = {41, 32, 19}; // compiler does initialization

3 41 32 19

a.length a[0] a[1] a[2]

This is schematic only,e.g., length may not befirst in memory.

Page 5: CS 340 Data Structures

Arrays of Primitives (cont.)• Here are two common (compile) errors:

• But this is OK:

int[] a;a[2] = 5; // a uninitialized

int[] b;int len = b.length; // b uninitialized

int[] a = {41, 32, 19};int[] b;b = a;int len = b.length;

Page 6: CS 340 Data Structures

Arrays of Objects

Stock[] a = new Stock[3]; // initialization to

3

a.length a[0] a[1] a[2]The array componentsa[0], a[1] and a[2] arenull () references.

class Stock { int sharesHeld = 0; double currentPrice = 100.00;}

a

Page 7: CS 340 Data Structures

Arrays of Objects

3 f0 f12 f24

a.length a[0] a[1] a[2]

for (int i = 0; i < 3; i++) a[i] = new Stock();

Stock Stock Stocka

Page 8: CS 340 Data Structures

Passing Arrays to Methodspublic class Stock { Stock() {} Stock(int s, double p, String name) { sharesHeld = s; currentPrice = p; symbol = name; } int sharesHeld = 0; double currentPrice = 100.00; String symbol; public String toString() { String s = new String(); s += sharesHeld + " shares of " + symbol + " at $" + currentPrice; return s; }}

Page 9: CS 340 Data Structures

Investor

public class Investor { Stock[] portfolio; Advisor ohTrustedOne; double value; Investor() {portfolio = new Stock[0];} Investor(Stock[] p, Advisor a) { portfolio = p; ohTrustedOne = a; value = ohTrustedOne.findValue(p); } // more below

Page 10: CS 340 Data Structures

Investor (cont.)

String describePortfolio() { String s = new String(); s += "My portfolio is: \n"; for (int i = 0; i < portfolio.length; i++) s += portfolio[i] + "\n"; s += "The total value is $" + value; return s; } void askAdvice() { ohTrustedOne.advise(portfolio); }}

Page 11: CS 340 Data Structures

Advisor

public class Advisor { double findValue(Stock[] p) { double value = 0; for (int i = 0; i < p.length; i++) value += p[i].currentPrice * p[i].sharesHeld; return value; } void advise(Stock[] p) { swindle(p); } void swindle(Stock[] p) { for (int i = 0; i < p.length; i++) p[i].sharesHeld /= 2; }}

Page 12: CS 340 Data Structures

Test Passing Arrays

public class TestInvestments { public static void main(String[] args) { Stock[] p = new Stock[] {new Stock(1000, 53.45, "GnMotr"),

new Stock(100, 29.05, "GenElec"), new Stock(220, 44.08, "GenMills")}; Advisor deweyCheethamAndHowe = new Advisor(); Investor sucker = new Investor(p, deweyCheethamAndHowe); System.out.println(sucker.describePortfolio()); sucker.askAdvice(); System.out.println(sucker.describePortfolio()); }}

Page 13: CS 340 Data Structures

Dangers in Passing Arrays• The called method gets a reference to the actual array,

and can modify it.• Using final is a possibility, but not in this example (at least

not easily).• If you are cautious, you can make a copy and send that.

Page 14: CS 340 Data Structures

Copies of Arrays• Shallowest: make a copy of the array reference• Shallow: make a new array of references of the same type

and size, and copy into it the existing array of references• Deep: the above, plus make copies of all the objects

themselves• The method System.arraycopy() does a shallow copy—

arghhh!

Page 15: CS 340 Data Structures

Deep Copy of an Array

Stock[] copyPortfolio() { // illustrates returning an array Stock[] copy = new Stock[portfolio.length]; for (int i = 0; i < portfolio.length; i++) { Stock s = new Stock(); s.currentPrice = portfolio[i].currentPrice; s.sharesHeld = portfolio[i].sharesHeld; s.symbol = new String(portfolio[i].symbol); copy[i] = s; } return copy; }

Page 16: CS 340 Data Structures

Aside: Cloning• Java doesn’t have the equivalent of C++’s copy

constructor, but does have cloning.• If a class implements the Cloneable interface, then you

can make a “duplicate copy” by calling clone().• To implement, override Object’s clone() method as a

public method in your class.• clone() returns an Object, which you can then cast to the

correct type.

Page 17: CS 340 Data Structures

Cloning Example

public class SimpleObject implements Cloneable { private int i; SimpleObject(int i) {this.i = i;} public String toString() { String s = new String(); s += "I'm a SimpleObject with i = " + i; s += " and address " + super.toString(); return s; }

Page 18: CS 340 Data Structures

Cloning Example (cont.)

public Object clone() { Object o = null; try { o = super.clone(); } catch(CloneNotSupportedException e) { System.out.println("SimpleClass can't clone."); } return o; }}

Page 19: CS 340 Data Structures

Cloning Example (cont.)

public class CloneTest { public static void main(String[] args) { SimpleObject s1 = new SimpleObject(1); System.out.println(s1); SimpleObject s2 = (SimpleObject) s1.clone(); System.out.println(s2); }}

One run produces this:I'm a SimpleObject with i = 1 and address SimpleObject@158269aI'm a SimpleObject with i = 1 and address SimpleObject@15829aa

Page 20: CS 340 Data Structures

Arrays Are “Type-Safe”• You explicitly declare the type of objects held in the array.

• The compiler checks to make sure your usage agrees with your declaration.

• A very common usage is to write a class hierarchy, then use an array of the type “highest” in the hierarchy (an array of Nodes, for example).

• Polymorphism is then used to work with the array elements.

Page 21: CS 340 Data Structures

The Arrays Class• In java.util• Provides many versions of the static methods:

• asList()• binarySearch()• equals()• fill()• sort() Versions of these for byte, char,

double, float, int, long, Objectand short. The Object versions ofbinarySearch() and sort() allowyou to specify a comparator.

Page 22: CS 340 Data Structures

Sorting Students public static void main(String[] args) { Student s1 = new Student("Fred", 3.0F); Student s2 = new Student("Sam", 3.5F); Student s3 = new Student("Steve", 2.1F);

Student[] students = new Student[] {s1, s2, s3}; for (int i = 0; i < students.length; i++) System.out.println(students[i].getName() + "\t" + students[i].getGpa()); Arrays.sort(students); for (int i = 0; i < students.length; i++) System.out.println(students[i].getName() + "\t" + students[i].getGpa()); }

Page 23: CS 340 Data Structures

Sorting Students (cont.)• This gives, as expected, the following:

Fred 3.0Sam 3.5Steve 2.1Steve 2.1Fred 3.0Sam 3.5

This example used the naturalcomparison method compareTo()that we provided in the Studentclass (which implemented theComparable interface). Thatcomparison method comparedgpas.

sort() also allows you to specifya different comparison methodif you want…

Page 24: CS 340 Data Structures

Sorting With a Comparator• The Comparator interface allows you to define “objects

that know how to compare two things.”• This interface expects you to define the compare()

method (and perhaps also the equals() method).• Let’s try it for Students.

Page 25: CS 340 Data Structures

Student Comparator

import java.util.*;

public class CompareStudentNames implements Comparator { public int compare(Object s1, Object s2) { return ((Student) s1).getName().compareTo( ((Student) s2).getName()); }}

Page 26: CS 340 Data Structures

Let’s Try It

Student s1 = new Student("Sam", 3.5F); // note I changed Student s2 = new Student("Steve", 2.1F); // the order of Student s3 = new Student("Fred", 3.0F); // the students!

Student[] students = new Student[] {s1, s2, s3}; for (int i = 0; i < students.length; i++) System.out.println(students[i].getName() + "\t" + students[i].getGpa()); Arrays.sort(students, new CompareStudentNames()); for (int i = 0; i < students.length; i++) System.out.println(students[i].getName() + "\t" + students[i].getGpa());

Page 27: CS 340 Data Structures

Now Try Filling

Arrays.fill(students, s1); for (int i = 0; i < students.length; i++) System.out.println(students[i].getName() + "\t" + students[i].getGpa()); students[1].setName("Gautam"); for (int i = 0; i < students.length; i++) System.out.println(students[i].getName() + "\t" + students[i].getGpa());

This gives:

Fred 3.0Fred 3.0Fred 3.0Gautam 3.0Gautam 3.0Gautam 3.0

This is probably not what we want!

Page 28: CS 340 Data Structures

The Java Container Classes• A container class object could be

• your bookcase• your photo album• your suitcase• your “junk drawer” in the kitchen• your apartment

• Containers hold Object references, so can be dangerous.• We can learn to live with danger…

Page 29: CS 340 Data Structures

Container Classes: Collection• List and Set, essentially, with some specializations. They

store individual objects, and give you • add(Object)• remove(Object)• contains(Object)• size()• other methods too

Page 30: CS 340 Data Structures

Container Classes: Map

• These hold pairs of things, a key and a value.• Pairs are held in a map, ordered by the key

• Methods include• containsKey(Object key)• containsValue(Object value)• put(Object key, Object value)• get(Object key)• remove(Object key)

Page 31: CS 340 Data Structures

The Java Collection Classes

interfaceCollection

interfaceList

interfaceSortedSet

AbstractSet

AbstractCollection interfaceSet

TreeSetHashSet

AbstractList

AbstractSequentialListArrayList

LinkedList

Page 32: CS 340 Data Structures

The Java Map Classes

interfaceMap

AbstractMap interfaceSortedMap

TreeMapHashMap WeakHashMap