1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

75
1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott

Transcript of 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

Page 1: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

1

Object-Oriented Programming (Java), Unit 9 (comes before Unit 20)

Kirk Scott

Page 2: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

2

Arrays, Vectors, and ArrayLists

• 9.1 Declaring and Processing Arrays• 9.2 Arrays: Copying, Passing as

Parameters, and Returning from Methods• 9.3 Array Examples• 9.4 The Java Collections Framework—

General Introduction• 9.5 Syntax Associated with the ArrayList

Class• 9.6 ArrayList Examples

Page 3: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

3

Why cover this?

• Some of this will be review of simple ideas about arrays.

• Some will be new. • This is because Java has classes for holding

collections of data.• Java also has special kinds of loops for

traversing the collections.• It is necessary to be familiar with ArrayLists and

how to traverse them, because all future Wari code examples will use these techniques.

Page 4: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

4

9.1 Declaring and Processing Arrays

Page 5: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

5

9.1.1 Mathematical Notation for Arrays

• Arrays are ordered collections of data items that are all of the same type.

• (a0, a1, …, ai, …, an-1)• In computer science it is customary to

have the initial subscript be 0.• Here is a simple example of an array

containing double values, with 13.2 in the 0th position, 5.5 in the 1st, and so on.

• (13.2, 5.5, …, 2.8, …, 6.7)

Page 6: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

6

9.1.2 Declaring and Constructing Arrays in Java

• Arrays in Java are objects.• Here are a declaration followed by

construction for an array which can hold a set of doubles.

• double[] myarray;• myarray = new double[10];

Page 7: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• As usual, declaration and construction can be combined in a single statement.

• double[] myarray = new double[10];• If the array is given the size 10, the array

indexing runs from 0 through 9.• It is a common mistake to think that indexing

starts at 1.• There is no harm in ignoring the 0th element, but

it is a mistake to try to access myarray[10] when such an element does not exist.

7

Page 8: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

8

9.1.3 Accessing Array Elements

• Once an array has been constructed, its elements can be accessed using an index value in square brackets.

• myarray[0] = 25.2;• double myvar = myarray[0];• myterminal.println(myarray[0]);

Page 9: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

9

9.1.4 Array Element Types and Initialization

• It is possible to declare arrays containing simple types as well as arrays containing object references.

• int[], double[], boolean[], String[]

• Arrays have default initialization.

• Numeric elements are 0, booleans are false, and object references are null.

Page 10: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

10

9.1.5 The Declaration of String[] args in main()

• The main() method takes an array of Strings, separated by spaces, as a parameter if a program is run from a command prompt.

• public static void main(String[] args)

Page 11: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

11

9.1.6 Arrays Containing Object References

• An array can be declared to contain elements of any kind of object.

• Cup6[] myCupArray = new Cup6[10];

• The syntax for calling methods on array elements is the same as before, although it looks a little unusual.

• int mycount = myCupArray[3].getSeedCount();

Page 12: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

12

9.1.7 Loops in Array Processing

• Using a loop index as an array index allows for consecutive access to array elements.

• for(int j = 0; j < 10; j++)• {• myarray[j] = j * j;• }

Page 13: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

13

9.1.8 Finding the length of an Array and Loop Limits

• The Array has a public final variable, length. You can go up.• for(int j = 0; j < myarray.length; j++)• {• myarray[j] = j * j;• }• Or you can go down.• for(int j = myarray.length – 1; j >= 0; j--)• {• …• }

Page 14: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

14

9.1.9 The Size of an Array is Fixed at Construction Time

• The size of an array is fixed at construction time.

• The size cannot be changed later on during the course of a program run.

Page 15: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

15

9.1.10 Two Dimensional Arrays

• The first subscript of an element represents its row and the second represents its column.

• This matrix has m rows and n columns with indexing beginning at 0 and an arbitrary element identified by ai,j.

Page 16: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

16

1,1,11,10,1

1,,1,0,

1,1,11,10,1

1,0,01,00,0

......

..................

......

..................

......

......

nmjmmm

nijiii

nj

nj

aaaa

aaaa

aaaa

aaaa

Page 17: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

17

9.1.11 Declaring and Constructing Two Dimensional Arrays in Java

• This statement declares and constructs an array with integer elements and 4 rows and 5 columns.

• int[][] myintarray = new int[4][5];

• Individual elements are accessed by specifying the index values for the row and column in square brackets.

• myintarray[2][4] = 95;

Page 18: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

18

9.1.12 Nested Loops in Two Dimensional Array Processing

• Two dimensional arrays can be processed conveniently using nested for loops.

• A two dimensional array is really a one dimensional array of references to a set of one dimensional arrays.

• In the code on the next overhead, myintarray.length gives the number of rows in myintarray.

• myintarray[0].length gives the number of columns in the 0th row (or any row) of myintarray.

Page 19: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• for(int i = 0; i < myintarray.length; i++)• {• for(int j = 0; j < myintarray[0].length; j+

+)• {• …• }• }

19

Page 20: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

20

9.2 Arrays: Copying, Passing as

Parameters, and Returning from Methods

Page 21: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

21

9.2.1 Copying Array References

• Here is an example of copying an array reference:

• double[] myarray = new double[10];• double[] yourarray;• yourarray = myarray;• The result is that there are two references

to the same array.

Page 22: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• If you did the following:• yourarray[0] = 3.0;• myterminal.println(myarray[0]);• You would expect to see the value 3.0

printed.• There is no effective difference between

myarray[0] and yourarray[0].

22

Page 23: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

23

9.2.2 Copying Array Contents

• It is also possible to make copies of the contents of arrays.

• double[] myarray = new double[10];• double[] yourarray = new double[myarray.length];

• for(j = 0; j < myarray.length; j++)• {• yourarray[j] = myarray[j];• }

Page 24: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

24

Java provides a static method for copying array contents:

• In order to have access to the method, import the System class:

• import java.lang.System;• This is the signature of the arraycopy method.• static void arraycopy• (Object src, int src_position,• Object dst, int dst_position,• int length)

Page 25: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• This is an example illustrating copying beginning at index position 0.

• System.arraycopy(myarray, 0, yourarray, 0, myarray.length);

25

Page 26: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

26

9.2.3 Passing Arrays as Parameters

• When a reference to an array is passed as an explicit parameter, any changes made to the array in the method are reflected in the calling program.

• Here is an example of a method with an array parameter.

• public class MyMethodContainer1• {• public static void squareArray(double[] anArray)• {• for(int j = 0; j < anArray.length; j++)• anArray[j] = anArray[j] * anArray[j];• }• }

Page 27: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

27

Here is an example call to the method:

• MyMethodContainer1.squareArray(myarray);

• Note that there are no square brackets used.

• myarray is a one dimensional array and the name alone refers to the array.

Page 28: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

28

9.2.4 Arrays as Return Values

• It is also possible for a method to have an array as its return type.• The returned array is created from scratch within the body of the

method.• Compare the following static method with the one above.• public class MyMethodContainer2• {• public static double[] squareArray(double[] anArray)• {• double[] returnArray = new

double[anArray.length];• for(int j = 0; j < returnArray.length; j++)• returnArray[j] = anArray[j] *

anArray[j];• return returnArray;• }• }

Page 29: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

29

Then the call in a program would take this form:

• double[] yourarray = MyMethodContainer2.squareArray(myarray);

• There is no need to separately create and give a size to yourarray.

• It is a reference which has assigned to it the created and sized array of doubles returned by the method.

Page 30: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

30

9.2.5 Passing Two Dimensional Arrays as Parameters

• Two dimensional arrays can also be passed as parameters.

• A reference to the array is passed by means of the name without square brackets.

Page 31: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

31

9.3 Array Examples

Page 32: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

32

9.3.1 Finding the Mean

• Write a class containing a static method to find the mean of a set of doubles stored in an array.

• Then write a program to test this method.

• Here is the mathematical formula for the mean:

n

xx

n

ii

1

Page 33: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

33

Here is a synopsis of a method to find the mean:

• It should return a double and it should take as parameters an array of doubles and an integer variable holding the count of how many data items are stored in the array.

• In the method declare a double variable to hold the mean and a double to hold a running sum.

• Now run a loop through the count, summing up the values in the array.

• Find the mean by dividing the sum by the count.• Return the mean.

Page 34: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

34

Here is a synopsis of a test program:

• Start with main() as usual.• Construct myterminal.• Declare a String variable and initialize it to

“yes”.• Declare an integer variable for the count

and initialize it to 0.• Declare a double to hold the mean.• Run a while loop as long as the answer is

not “no”.• In the loop, prompt the user for a value.

Page 35: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• Take in a double from myterminal and put it into the array using the current count as the index.

• Increment the count.• Ask the user whether or not they want to

go again.• Take in the String answer from

myterminal. This is the bottom of the loop.• Then call the method to get the mean.• Print the mean.

35

Page 36: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

36

The solution classes, which make use of arrays, follow.

• public class MeanClass• {• public static double myMean(double[] inArray, int

count)• {• double mean;• double sum = 0.0;• int i;• for(i = 0; i < count; i++)• {• sum = sum + inArray[i];• }• mean = sum / count;• return mean;• }• }

Page 37: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

37

• public class MeanTestProg• {• public static void main(String[] args)• {• MyTerminalIO myterminal = new MyTerminalIO();• double[] dataArray = new double[100];• String answer = "yes";• int dataCount = 0;• double dataMean;• myterminal.println("This program will handle a data set of

up to 100 values.");• while(!answer.equals("no") && dataCount < 100)• {• myterminal.println("Enter a value.");• dataArray[dataCount] = myterminal.getDouble();• dataCount++;• myterminal.println("Go again? (yes/no)");• answer = myterminal.getString();• }• dataMean = MeanClass.myMean(dataArray, dataCount);• myterminal.println("The mean of the data set is: " +

dataMean);• }• }

Page 38: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

38

9.3.2 Cups with Arrays Containing Seeds

• This UML diagram illustrates this example.

Cup7

Seed7

1

-has0..*

Page 39: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

39

This is the seed class for the example:

• public class Seed7• {• private String seedColorName;• public Seed7(String seedColorNameIn)• {• seedColorName = seedColorNameIn;• }• public String getSeedColorName()• {• return seedColorName;• }• }

Page 40: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

40

This is the cup class for the example:

• The seedArray instance variable in this class contains references to seeds.• public class Cup7• {• private int seedCount;• private int maxSeedCount;• private Seed7[] seedArray;• public Cup7(int maxSeedCountIn)• {• seedCount = 0;• maxSeedCount = maxSeedCountIn;• seedArray = new Seed7[maxSeedCount];• }• public int getSeedCount()• {• return seedCount;• }

Page 41: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

41

• public boolean addSeed(Seed7 seedIn)• {• if(seedCount < maxSeedCount)• {• seedArray[seedCount] = seedIn;• seedCount++;• return true;• }• else• return false;• }• public Seed7 removeSeed()• {• if(seedCount > 0)• {• seedCount--;• Seed7 temp = seedArray[seedCount];• seedArray[seedCount] = null;• return temp;• }• else• return null;• }• }

Page 42: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

42

This program tests the cup and seed classes.

• public class TestCup7AndSeed7• {• public static void main(String[] args)• {• Cup7 myCup = new Cup7(5);• Seed7 aSeed;• int howManySeeds;• boolean okToEnter = true;• MyTerminalIO myterminal = new MyTerminalIO();• while(okToEnter)• {• aSeed = new Seed7("blue");• okToEnter = myCup.addSeed(aSeed);• }• howManySeeds = myCup.getSeedCount();• for(int i = 0; i < howManySeeds; i++)• {• aSeed = myCup.removeSeed();• myterminal.println(aSeed.getSeedColorName());• }• }• }

Page 43: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

43

9.4 The Java Collections Framework—General Introduction

• The Java collections framework provides a consistent set of standards for various kinds of classes, instances of which serve as containers for objects.

• Collections in general fall into the categories of sets, lists, and queues, with sets possibly being sorted.

• The Array class is the most basic kind of container for object references.

• The ArrayList class is a kind of container which is more flexible, which will be used for further examples.

Page 44: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

44

• Different collections classes also depend on the Map interface.

• A map implements a relationship between one set of values and another.

• A map may be either unsorted or sorted.

Page 45: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• The collections framework overview in the Java documentation gives the interfaces and their implementations in a table.

• The vertical axis includes the set, list, and map interfaces.

• It turns out that queues are subsumed by lists.

45

Page 46: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• The horizontal axis gives the major groups of implementations: Hash table, resizable array, etc.

• The table entries are classes in the Java API.

• Not every interface has each kind of implementation, and conversely, not every kind of implementation implements each interface.

46

Page 48: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

48

9.5 Syntax Associated with the ArrayList Class

Page 49: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

49

9.5.1 Importing the Class

• The ArrayList class has to be imported in order to be used in a program.

• import java.util.ArrayList;

Page 50: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

50

9.5.2 Angle Bracket Notation to Specify Element Types

• In a program which uses a collection class, declarations with angle bracket notation specify what kinds of elements the collection contains.

• The following line of code would declare and construct an ArrayList containing references to Cup7 objects.

• ArrayList<Cup7> mycollection = new ArrayList<Cup7>();

• If it is desirable for the ArrayList to contain simple types like integers or doubles, the values should be stored in instances of the wrapper classes Integer and Double.

• ArrayList<Double> mycollection = new ArrayList<Double>();

Page 51: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

51

9.5.3 For Each Loops—Elements Cannot be Added to or Removed from a Collection

• Traversing all of the elements of an ArrayList can be done with a “for each” loop.

• In the for statement a local reference named someCup is declared.

• The for statement also contains a colon followed by the name of the collection to be accessed.

• The type of the local reference agrees with the type of the elements of the collection.

Page 52: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• The loop runs through all of the elements of mycollection, successively assigning references of its elements to the local reference, someCup.

• The loop delivers access to successive elements of the collection, but it is not possible to call methods on the collection itself.

• This means that it is not possible to add elements to, or remove them from the collection when using this syntax.

52

Page 53: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

53

For each loop example:

• for(Cup7 someCup: mycollection)• {• myterminal.println(someCup);• }

Page 54: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

54

9.5.4 Iterators and Collections

• Traversing the elements of a collection is known as iteration.

• The Java collections framework includes interfaces named Iterator and Iterable.

• They support the traversal of a collection where it is possible to alter the collection while processing it.

Page 55: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• The Iterable interface contains one method, named iterator().

• Calling this method on a collection class returns a reference to an iterator.

• Angle bracket notation is used to specify what kinds of elements the iterator is dealing with.

55

Page 56: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• If mycollection contains Cup7 elements, then the declaration of an iterator for the collection would take this form:

• Iterator<Cup7> myiterator = mycollection.iterator();

56

Page 57: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

57

9.5.5 Iterator Methods

• Three different methods can be called on an iterator.

• boolean hasNext()• Returns true if the iteration has more

elements.

Page 58: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• E next()• Returns the next element (of type E) in the

iteration. • Calling this method repeatedly until the

hasNext() method returns false will return each element in the underlying collection exactly once.

58

Page 59: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• void remove()• Removes from the underlying collection

the last element returned by the iterator. • This method can be called only once per

call to next.

59

Page 60: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

60

9.5.6 While Loops with Iterators—Elements can be Added to or Removed from a Collection

• Assume that mycollection contains references to the Cup7 class.

• The iterator for the collection is obtained before the loop.

• The test for continuing to loop is a call to hasNext().

• Example code is given on the next overhead.• In the body of the loop, the call to next() returns

a reference to the next element, and the call to remove() causes that element to be removed from the collection.

Page 61: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

61

This example removes from mycollection all elements which contain 0 or fewer seeds:

• import java.util.Iterator;• …• Iterator<Cup7> myiterator = mycollection.iterator();• Cup7 someCup;• while(myiterator.hasNext())• {• someCup = myiterator.next();• if(someCup.getSeedCount() <= 0)• myiterator.remove();• }

Page 62: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

62

9.5.7 For Loops with Iterators—Elements can be Added to or Removed from a Collection

• The first part of the for statement obtains the iterator for the collection.

• The second part of the for statement causes the iteration to continue as long as there is another element in the collection

• import java.util.Iterator;• …• for(Iterator<Cup7> myiterator = mycollection.iterator(); myiterator.hasNext(); )• {• if((myiterator.next().getSeedCount()) <= 0)• myiterator.remove();• }

Page 63: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

63

9.6 ArrayList Examples

Page 64: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

64

9.6.1 Finding the Mean

• Shown below is a solution to the problem of finding the mean of a data set using an ArrayList instead of an Array.

• This illustrates four general things.• 1. There is no limit on the number of

elements in an ArrayList, so there is no limit on the size of the data set.

• 2. It is possible to keep track of the number of elements in the method rather than in the main() program.

Page 65: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

• 3. The add() method adds elements to the collection.

• 4. Java includes a feature called autoboxing.

• In the program it’s not necessary to construct instances of the class Double and assign double values to their instance variables.

• In those cases where a reference to a Double is needed, the system will create the needed object and do the value assignment automatically.

65

Page 66: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

66

• import java.util.ArrayList;• public class CollectionMeanClass• {• public static double myMean(ArrayList<Double>

dataSetIn)• {• double mean;• double sum = 0.0;• int dataCount = 0;• for(Double someDouble: dataSetIn)• {• dataCount++;• /* This is where autoboxing occurs. */• sum = sum + someDouble;• }• mean = sum / dataCount;• return mean;• }• }

Page 67: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

67

• import java.util.ArrayList;• public class CollectionMeanTestProg• {• public static void main(String[] args)• {• MyTerminalIO myterminal = new MyTerminalIO();• ArrayList<Double> dataSet = new ArrayList<Double>();• String answer = "yes";• double dataMean;• while(!answer.equals("no"))• {• myterminal.println("Enter a value.");• dataSet.add(myterminal.getDouble());• myterminal.println("Go again? (yes/no)");• answer = myterminal.getString();• }• dataMean = CollectionMeanClass.myMean(dataSet);• myterminal.println("The mean of the data set is: "

+ dataMean);• }• }

Page 68: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

68

9.6.2 Cups with ArrayLists Containing Seeds

• This UML diagram illustrates this example.

Cup8

ArrayList

Seed8

1

-has1

1

-has0..*

Page 69: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

69

This is the seed class for the example:

• import java.awt.Color;• public class Seed8• {• private Color seedColor;• public Seed8(Color aColor)• {• seedColor = aColor;• }• public Color getColor()• {• return seedColor;• }• }

Page 70: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

70

This is the cup class for the example:

• import java.util.ArrayList;• public class Cup8• {• private ArrayList<Seed8> cupContents;• public Cup8()• {• cupContents = new ArrayList<Seed8>();• }• /* The Cup8 class doesn’t have a seedCount instance

variable. It relies on the size() method of the ArrayList class to tell how many elements are in it. */

• public int getSeedCount()• {• return cupContents.size();• }

Page 71: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

71

• /* This method returns a reference to the ArrayList containing the seeds in the cup. */

• public ArrayList<Seed8> getContents()• {• return cupContents;• }• public void addSeed(Seed8 aseed)• {• cupContents.add(aseed);• }• /* Notice that the ArrayList remove() method is

different from the Iterator remove() method. ArrayLists are indexed like arrays, and when removing an element, it’s necessary to specify the index. This method removes the last element of the ArrayList. */

• public Seed8 removeSeed()• {• return cupContents.remove(cupContents.size() - 1);• }• }

Page 72: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

72

This is an applet that uses the cup and seed classes.

• import javax.swing.JApplet;• import java.awt.Graphics;• import java.awt.Graphics2D;• import java.awt.geom.Rectangle2D;• import java.awt.geom.Ellipse2D;• import java.awt.Color;• import java.util.Random;

Page 73: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

73

• public class TestCup8AndSeed8 extends JApplet• {• public void paint(Graphics g)• {• Graphics2D g2 = (Graphics2D) g;• Cup8 mycup = new Cup8();• Random generator = new Random();• Seed8 someSeed;• ArrayList<Seed8> seedsInCup;• double randX, randY, seedX, seedY;• someSeed = new Seed8(Color.red);• mycup.addSeed(aseed);• someSeed = new Seed8(Color.green);• mycup.addSeed(aseed);• someSeed = new Seed8(Color.blue);• mycup.addSeed(aseed);

Page 74: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

74

• Rectangle2D.Double myrectangle = new Rectangle2D.Double(20, 20, 100, 100);

• g2.draw(myrectangle);• seedsInCup = mycup.getContents();• for(Seed8 someSeed: seedsInCup)• {• g2.setColor(someSeed.getColor());• randX = generator.nextDouble();• randY = generator.nextDouble();• seedX = 20 + randX * 90.0;• seedY = 20 + randY * 90.0;• Ellipse2D.Double mydot = new

Ellipse2D.Double(seedX, seedY, 10, 10);• g2.fill(mydot);• }• }• }

Page 75: 1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.

75

The End