jugglingwithdata: arrays and collections · (c)schmiedecke 06 inf1-8a-arrays and collections 5 data...

37
Juggling with Data: Arrays and Collections Data Collections and Abstract Data Types Arrays Using Arrays to Implement Abstract Data Types (optionally: Sorting and Searching Arrays)

Upload: others

Post on 14-Jun-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

Juggling with Data:Arrays and Collections

� Data Collections and Abstract Data Types

� Arrays

� Using Arrays to Implement Abstract Data Types

� (optionally: Sorting and Searching Arrays)

Page 2: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

I. Data Collections

and Abstract Data Types

Page 3: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 3

Interacting Units:

� A Program consists of:

� a central problem solving object (class with main-method) and assistance objects

� Assistance may mean offering operations (tell me the time in New York, find out how many users are logged on...)

� or data management (remember the following numbers, deduce100€ from account, find out customer's address)

Page 4: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 4

Example Context:Transport Company

Page 5: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 5

Data Container Objects

� Program has to manage a number of objects of one type

� as a group, or collection.

� Defines an aggregatetype to do themanagement

� call it container orcollection type

class VehiclePool {

Car car1 = new Car(),

car2 = new Car(),

car3 = new Car(),

car4 = new Car(),

car5 = new Car(),

car6 = new Car();

Truck truck1 = new Truck(),

truck2 = new Truck(),

truck3 = new Truck();

Bike bike1 = new Bike();

}

Page 6: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 6

Generalized Collection Type

� Specialized aggregate type with fixed number of members is of limited use

� Better: Type that stores a variable number of elements.

� Standard operations: - add element- read / search for element- remove / delete element- number of entries- (possibly) max. number of entries

� Which element type for the VehiclePool?- Object, Car, Truck, Bike?- often use a specific superclass: Vehicle

Page 7: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 7

Define a Collection Interface

interface VehiclePoolType {

public void add(Vehicle vh);

public int search();

public Fahrzeug show();

public void remove();

public int number();

}

interface VehiclePoolType {

public void add(Vehicle vh);

public void remove(Vehicle vh);

public int number();

public Vehicle search(…);

}

Vehicle

TruckCar Bike

element typeVehicle

Page 8: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 8

Collection can have Different Characteristics

� How are the elements stored?

– sorted / unsorted

– with / without multiple entries

– with / without erasing

– with / without number limit

� How are elements found?

– by index

– by key

– by search expression ("query")

Page 9: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 9

Indexed Collection

interface IndexedVehiclePoolType {

public int add(Vehicle vh);// yields index

public void remove(int index);

public int number();

public int search(Vehicle vh);// model object

public Vehicle show(int index);

}

Car park:

numbered places

Page 10: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 10

The Indexed Collection Interface specifies an Abstract Data Type

interface IndexedVehiclePoolType {

public int add(Vehicle vh);// yields index

public void remove(int index);

public int number();

public int search(Vehicle vh);// model

object

public Vehicle show(int index);

}

Let's learn how to implement such collections...

Data Type:

- type with non-trivial state- typical data operations

Abstract:- different implementationspossible

Page 11: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

II. Arrays

Page 12: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 12

Data Arrays

• resemble the actual memory

usage

• directly support indexed

collections

• available in all programming

languages

An array is an indexed, fixed length sequence of

elements of identical type.

0147B0147C

0147D

0147E0147F

0148001481

Page 13: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 13

Instead of:

class VehiclePool {

Car car1 = new Car(),

car2 = new Car(),

car3 = new Car(),

car4 = new Car(),

car5 = new Car(),

car6 = new Car();

Truck truck1 = new Truck(),

truck2 = new Truck(),

truck3 = new Truck();

Bike bike1 = new Bike();

}

Every car has itsown name,

similarities are pure coincidence.

Page 14: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 14

...now write:class VehiclePool {

Car[] cars = new Car[6];

Truck[] trucks = new Truck[5];

Bike[] bikes = new Bike[3];

// Fill with elements, e.g.in constructor

public VehiclePool () {

cars[0] = new Car(); trucks[0] = new Truck();

cars[1] = new Car(); trucks[1] = new Truck();

cars[2] = new Car(); trucks[2] = new Truck();

cars[3] = new Car();

cars[4] = new Car(); bikes[0] = new Bike();

cars 5] = new Car();

// trucks[3], trucks[4] and bikes[1], bikes[2]

// remain empty (null)

}

}

like empty garages!

move in please!

Page 15: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 15

Array Facts:

� The element type can be a class or a primitive type:

Car[] carpark = new Car[25];int[] personalKey = new int[1000];

� Arrays are objects, independant of their element type

Object dataContainer = new int[10000];

� Indexing starts with 0 (of course...)

personalKey[0] up to personalKey[999]

� Each array has an attribute length containing its size:

personalKey.length // for reading only!

Page 16: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 16

Java 5 Iterating Loop

� So here is the standard for loop for traversing arrays:

for (int index=0; index<array.length; index++)

operationOn(array[index]);

� And here is the Java 5 simplified iterating loop:

for (Element element : array)operationOn(element);

- Read: "element in array"- Does not provide an index

Page 17: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 17

... once again VehiclePool:

class VehiclePool {

Car[] cars = new Car[6];

Truck[] trucks = new Truck[5];

Bike[] bikes = new Bike[3];

// constructor - fill with elements

public VehiclePool() {

for (int i=0;i<cars.length;i++)

cars[i] = new Car();

for (int i=0; i<3; i++)

trucks[i] = new Truck();

bikes[0] = new Bike();

}

}

standard"parking

loop"

Page 18: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 18

... once again VehiclePool:

class VehiclePool {

Car[] cars = new Car[6];

Truck[] trucks = new Truck[5];

Bike[] bikes = new Bike[3];

// constructor - fill with elements

public VehiclePool() {

for (Car nextcar : cars)

nextcar = new Car();

for (int i=0; i<3; i++)

trucks[i] = new Truck();

bikes[0] = new Bike();

}

}

Java 5"parking

loop"

Page 19: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 19

More Arrays Facts:

� Access with illegal index �

IndexOutOfBoundsException. (Type RuntimeException – catching not enforced)

� try { cars[i] = new Car(); } catch (IndexOutOfBoundsException e){ System.err.println

("there are only "+cars.length+" garages!"); }

� Special initialization construct: Array Initializer

int[] registration = {1988, 1992, 1999};String[] person = {"manager", name, dept.toString()};

Page 20: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 20

Multidimensional Arrays:

� Multidimensional array: "array of arrays"

� Size only required for the outermost dimension

� multidimensional arrays need not be rectangular:

int triangle[][] = new int[10][];

for (int i=0; i< triangle.length; i++) {

triangle[i] = new int[i+1];

for (int j=0; j<i+1; j++)

triangle[i][j] = i+j;

}

Page 21: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

III. Implementing Abstract Data

Types using Arrays

Page 22: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 22

Indexed Collection

interface IndexedVehiclePoolType {

public int add(Vehicle vh);

// yields index

public int search(Vehicle vh);

// model object

public Vehicle show(int index);

public void remove(int index);

public int number();

}

Car park:

numbered places

Page 23: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 23

Implementation using an Array

class VehicleArray implements IndexedVehiclePoolType {

// private attributes

private Vehicle[] vehicles;

private int number = 0;

// Default constructor, fixed size

public VehicleArray() {

vehicles = new Vehicle[50];

}

// constructor with size parameter

public VehicleArray(int size) {

vehicles = new Vehicle[size];

}

Page 24: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 24

// add if not full

public int add(Vehicle vh) {

if (number >= vehicles.length) return -1; // signal failure

vehicles[number] = vh;

number++;

return number-1;

}

public int number()

{ return number; }

// read if existing

public Vehicle read(int index) {

if (index < 0 || index >= vehicles.length)return null; // signal failure

return vehicles[index];

}

Page 25: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 25

public int search(Vehicle vh) // model object

{

if (vh==null) return -99; // signal no model object

for (int i=0; i<number; i++)

if (vehicles[i].equals(vh)) return i; // found

return -1; // not found

}

// remove and compactify

public void remove(int index) {

if (index>=0 || index<number)for (int i=index; i<number-1; i++)

vehicles[i] = vehicles[i+1]; // move up

vehicles[number-1] = null;

number --;

else; // no action

}

} // end of class

Page 26: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

Signalling error conditions is not

satisfactory:

Let's learn about Exceptions!

-- insert lecture 8b --

Page 27: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 27

Implementation using Exceptions

class CarPark implements IndexedCarParkType {

// private attributes

private Car[] cars; // data structure

private int carCount = 0; // semantic helper

// Default constructor, fixed size

public CarPark() {

cars = new Car[50];

}

// constructor with size parameter

public CarPark(int size) {

cars = new Cars[size];

}

Page 28: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 28

// add if not full

public int add(Car c) throws FullException {

if (carCount >= cars.length) throw new FullException();

vehicles[carCount] = c;

carCount++;

return carCount-1;

}

public int carCount()

{ return carCount; }

// read if existing

public Vehicle show(int index)throws NotFoundException, IllegalIndexException {

if (index >= carCount)throw new NotFoundException();

try { return cars[index]; }

catch (ArrayIndexOutOfBoundsException ex)

{ throw new IllegalIndexException(); }

}

public class FullException

extends Exception {}

public class IllegalIndexException

extends Exception {}

public class NotFoundException

extends Exception {}

but mind the order of exception detection...

Page 29: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 29

public int search(Car car) // model objectthrows NotFoundException {

if (car==null) throw new NoObjectException();

for (int i=0; i<carCount; i++)

if (cars[i].equals(car)) return i; // found

throw new NotFoundException(); // not found

}

// remove and compactify

public void remove(int index)

throws IllegalIndexException{

if (index <0 || index >= carCount)throw new IllegalIndexException();

for (int i=index; i<carCount-1; i++)

cars[i] = cars[i+1]; //close gap

carCount--;

cars[carCount] = null;

}

} // end of class

class NotFoundException

extends Exception {}

class NoObjectException

extends RuntimeException{}

Page 30: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 30

Use the CarPark Type

class UseCarPark {

public static void main(String[] args) {

CarPark smallCarPark = new CarPark(12);

try {

for (int i=0; i<13; i++)

smallCarPark.add(new Car());

} catch (FullException ex)

{ System.out.println("Car park is full, sorry!"); }

}

}

This main method could be moved into any class... even the CarPark class itself.

Page 31: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 31

Data Structures – Data Types

Concepts for storing data:

• Data structure:– Object which can be used to store data

– Example: int[] dataStruct = new int[100];

• Data type:– Type for creating data structures– e.g. an array: int []

instances are data structures for storing a series of integers

– or some „record class “:

public class Address {String name;String firstName;int age;// …

}

instances are data structures for storing two Strings and an integer

Page 32: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

IV. Sorting and Searching Arrays

Page 33: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 33

Sorting an Array

�A method sort() is added to the class

VehiclePool

�Requirement:

Vehicle must have a method bigger().

�Trap: All previous indices become invalid

after sorting.

Page 34: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 34

Bubble Sortpublic int sort () { // bubblesort

// idea: "heavy" elements sink

for (int i=size-1; i>0; i--) { // backward

Vehicle vhi = vehicles[i];

for (int k=i-1; k>=0; k--) {

Vehicle vhk = vehicles[k]; // predecessor

if (vhk.bigger(vhi)) {

//swap:

vehicles[i] = vhk;

vehicles[k] = vhi;

vhi = vhk; // new comparison value

}

} // for (k

} // for (i

} // sort

���� Rephrase: light elements float...

Page 35: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 35

Searching a Sorted Array

� Binary search (BinSearch) is the most efficientalgorithm.

� Only works on a compact array (no gaps)

� Phone book technique: Find out in which half of thearray the element belongs, then in which half of the

half etc.

Page 36: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

(c)schmiedecke 06 inf1-8a-Arrays and Collections 36

Binary Search

public int search(Vehicle vh) { // BinSearch

int min = 0, max = size - 1;

while (min <= max) {

int middle = (min + max) / 2;

Vehicle vhm = vehicles[middle];

if (vhm.bigger(vh)) {

max = middle – 1; // search upper half

else if (vh.equals(vhm))

return middle;

else

min = middle + 1; // search lower half

} // while

return –1; // not found

} // search

Page 37: JugglingwithData: Arrays and Collections · (c)schmiedecke 06 inf1-8a-Arrays and Collections 5 Data Container Objects Program has to manage a number of objects of one type as a group

That's enough –

☺☺☺☺Next week we will learn about alternatives to arrays and more

general data types