Transcript lect10

CS1101: Programming Methodology
http://www.comp.nus.edu.sg/~cs1101x/
Lecture 10: Arrays

After you have read and studied this chapter, you
should be able to






Manipulate a collection of data values, using an array.
Declare and use an array of primitive data types in
writing a program.
Declare and use an array of objects in writing a
program
Define a method that accepts an array as its parameter
and a method that returns an array
Describe how a two-dimensional array is implemented
as an array of arrays
Manipulate a collection of objects, using lists
CS1101X: Lecture #10
Acknowledgement: Thomas Wu.
2
Array Basics



An array is a collection of data values.
If your program needs to deal with 100 integers,
500 Account objects, 365 real numbers, etc., you
will use an array.
In Java, an array is an indexed collection of data
values of the same type.
CS1101X: Lecture #10
3
Arrays of Primitive Data Types

Array Declaration
<data type> [ ] <variable>
<data type>
<variable>[ ]

Array Creation
<variable>

// variation 1
// variation 2
= new <data type> [ <size> ]
Example
Variation 1
Variation 2
double[ ] rainfall;
double rainfall [ ];
rainfall
rainfall
= new double[12];
= new double[12];
An array is like an object!
CS1101X: Lecture #10
4
Accessing Individual Elements

Individual elements in an array accessed with the indexed
expression.
double[] rainfall = new double[12];
rainfall
0
1
2
3
The index of the first
position in an array is 0.
CS1101X: Lecture #10
4
5
6
rainfall[2]
7
8
9
10
11
This indexed expression
refers to the element at
position #2
5
Motivation (1/3)

Task: Find the minimum value of 3 integers
int min;
if ((value1<=value2) && (value1<=value3))
min = value1;
else if ((value2<=value1) && (value2<=value3))
min = value2;
else if ((value3<=value1) && (value3<=value2))
min = value3;

What if the list is big?

Code will be longer – the logical expression in each ‘if’ statement
will be longer and more complex.
CS1101X: Lecture #10
6
Motivation (2/3)

Consider this algorithm
int min = value1;
if (value2 < min) min = value2;
if (value3 < min) min = value3;

What if the list is big?

Code will still be longer, but if we make use of the regular pattern
and the array structure for the data, we can ‘roll’ the if statements
into a loop.
CS1101X: Lecture #10
7
Motivation (3/3)

Using the array structure
int min = value[0];
if (value[1] < min) min = value[1];
if (value[2] < min) min = value[2];

Rolling into a loop using array subscript/index
int min = value[0];
for (int k = 1; k < 3; ++k) {
if (value[k] < min)
min = value[k];
}

The above code can be modified easily for a bigger list.
CS1101X: Lecture #10
8
Basic Terminology






An array is a form of ordered list.
A list is composed of elements.
Elements in a list have a common name.
The list as a whole is referenced through the
common name.
List is homogeneous, that is, list elements are of
the same type — the base type.
Elements of a list are referenced by subscripting
(indexing) the common name.
CS1101X: Lecture #10
9
Java Array Features





Subscripts are denoted as expressions within square
brackets: [ ]
Base (element) type can be any type
Size of array can be specified at run time
Index type is integer and the index range must be 0 ...
n-1, where n is the number of elements
Automatic bounds checking



Ensures any reference to an array element is valid
Data field length specifies the number of elements in
the list
Array is an object

Has features common to all other objects
CS1101X: Lecture #10
10
Example (1/2)

Definitions
char[] c;
int[] value = new int[10];
String[] s = new String[2];

Causes



Array object variable c is un-initialized.
Array object variable v references a new 10-element list of
integers. Each of the integers is by default initialized to 0.
Array object variable s references a new 2-element list of strings.
Each of the strings is by default initialized to null.
c
-
s
null null
value
0
CS1101X: Lecture #10
0
0
0
0
0
0
0
0
0
11
Example (2/2)

For simplicity, sometimes we represent
value
0
0
0
0
0
0
0
0
0
0
simply as
value
CS1101X: Lecture #10
0
0
0
0
0
0
0
0
0
0
12
Array Processing – Sample 1
double[] rainfall = new double[12];
The public constant
length returns the
capacity of an array.
double annualAverage,
sum = 0.0;
for (int i = 0; i < rainfall.length; i++) {
rainfall[i] = Double.parseDouble(
JOptionPane.showinputDialog(null,
"Rainfall for month " + (i+1) ) );
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
CS1101X: Lecture #10
13
Array Processing – Sample 2
double[] rainfall = new double[12];
String[] monthName = new String[12];
monthName[0] = "January";
monthName[1] = "February";
…
The same pattern
for the remaining
ten months.
double annualAverage, sum = 0.0;
for (int i = 0; i < rainfall.length; i++) {
rainfall[i] = Double.parseDouble(
JOptionPane.showinputDialog(null,
"Rainfall for "
+ monthName[i] ));
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
CS1101X: Lecture #10
The actual month
name instead of a
number.
14
Array Processing – Sample 3

Compute the average rainfall for each quarter.
//assume rainfall is declared and initialized properly
double[] quarterAverage = new double[4];
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 3; j++) {
sum += rainfall[3*i + j];
// compute the sum of
// one quarter
}
quarterAverage[i] = sum / 3.0;
// Quarter (i+1) average
}
CS1101X: Lecture #10
15
Array Initialization (1/2)

Like other data types, it is possible to declare and
initialize an array at the same time.
int[] number = { 2, 4, 6, 8 };
double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,
9.00, 3.123, 22.084, 18.08 };
String[] monthName = { "January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };
number.length
samplingData.length
monthName.length
CS1101X: Lecture #10
4
9
12
16
Array Initialization (2/2)
int[] number = { 2, 4, 6, 8 };
is equivalent to
int[] number = new int[4];
number[0] = 2;
number[1] = 4;
number[2] = 6;
number[3] = 8;

Member length


A public final data field called length.
Size of the array.
CS1101X: Lecture #10
17
Coin Change Problem (1/2)

Rewrite the code for coin change problem (Lecture #0,
slide 56), using an array
int coins[6] = { 100, 50, 20, 10, 5, 1 };

Without array:
int amt = scanner.nextInt();
int numberOfCoins = 0;
numberOfCoins += amt/100;
amt %= 100;
numberOfCoins += amt/50;
amt %= 50;
CS1101X: Lecture #10
numberOfCoins += amt/20;
amt %= 20;
numberOfCoins += amt/10;
amt %= 10;
numberOfCoins += amt/5;
amt %= 5;
numberOfCoins += amt/1;
amt %= 1;
18
Coin Change Problem (2/2)

With array:
int amt = scanner.nextInt();
int numberOfCoins = 0;
int coins[] = { 100, 50, 20, 10, 5, 1 };
for (int i = 0; i < 6; i++) {
numberOfCoins += amt/coins[i];
amt %= coins[i];
}
CS1101X: Lecture #10
19
Index Out Of Bounds

Code
int[] b = new int[100];
b[-1] = 123;
b[100] = 9;

Causes
 Array

Each element is initialized to 0
 Two



variable to reference a new list of 100 integers
exceptions to be thrown
-1 is not a valid index – too small
100 is not a valid index – too large
IndexOutOfBoundsException
CS1101X: Lecture #10
20
Variable-size Declaration


In Java, we are not limited to fixed-size array
declaration.
The following code prompts the user for the size of
an array and declares an array of designated size:
int size;
int[] number;
size = Integer.parseInt(JOptionPane.showInputDialog(null,
"Size of an array:"));
number = new int[size];
CS1101X: Lecture #10
21
Arrays of Objects



In Java, in addition to arrays of primitive data
types, we can declare arrays of objects
An array of primitive data is a powerful tool, but an
array of objects is even more powerful.
The use of an array of objects allows us to model
the application more cleanly and logically.
CS1101X: Lecture #10
22
Method main() (1/2)

Usual signature for method main
public static void main(String[] args)


args is an array of String objects.
Consider
public class Demo {
public static void main(String[] args) {
for (int i = 0; i < args.length; ++i) {
System.out.println("args[" + i + "]: "
+ args[i]);
}
}
}
CS1101X: Lecture #10
23
Method main() (2/2)

This allows user to specify command line arguments when
executing the program.
java Demo 10 ABC-D Hello "Ice Cream"

Output
args[0]:
args[1]:
args[2]:
args[3]:
CS1101X: Lecture #10
10
ABC-D
Hello
Ice Cream
24
The Person Class

We will use Person objects to illustrate the use of
an array of objects.
Person latte;
latte = new Person( );
The Person class
supports the set methods
and get methods.
latte.setName("Ms. Latte");
latte.setAge(20);
latte.setGender('F');
System.out.println( "Name: " + latte.getName() );
System.out.println( "Age : " + latte.getAge() );
System.out.println( "Sex : " + latte.getGender() );
CS1101X: Lecture #10
25
Creating an Object Array (1/3)
Code
A
Person[ ]
person;
person = new Person[20];
person[0] = new Person( );
Only the name person is
declared, no array is
allocated yet.
person
State
of
Memory
After A is executed
CS1101X: Lecture #10
26
Creating an Object Array (2/3)
Code
Person[ ]
B
person;
person = new Person[20];
person[0] = new Person( );
Now the array for storing
20 Person objects is
created, but the Person
objects themselves are
not yet created.
person
0
1
2
3
4
16 17 18 19
State
of
Memory
After B is executed
CS1101X: Lecture #10
27
Creating an Object Array (3/3)
Code
Person[ ]
person;
person = new Person[20];
C
person[0] = new Person( );
One Person object is
created and the reference
to this object is placed in
position 0.
person
0
State
of
Memory
1
2
3
4
16 17 18 19
Person
After C is executed
CS1101X: Lecture #10
28
Person Array Processing – Sample 1

Create Person objects and set up the person array.
String
name, inpStr;
int
age;
char
gender;
for (int i = 0; i < person.length; i++) {
name
= inputBox.getString( "Enter name:" );
age
= inputBox.getInteger( "Enter age:" );
// read in data values
inpStr = inputBox.getString( "Enter gender:" );
gender = inpStr.charAt(0);
person[i] = new Person( );
// create a new Person and assign values
person[i].setName(name);
person[i].setAge(age);
person[i].setGender(gender);
}
CS1101X: Lecture #10
29
Person Array Processing – Sample 2

Find the youngest and oldest persons.
int minIdx = 0;
// index to the youngest person
int maxIdx = 0;
// index to the oldest person
for (int i = 1; i < person.length; i++) {
if ( person[i].getAge() < person[minIdx].getAge() ) {
minIdx = i;
// found a younger person
} else if (person[i].getAge() > person[maxIdx].getAge() ) {
maxIdx = i;
// found an older person
}
}
// person[minIdx] is the youngest and person[maxIdx] is the oldest
CS1101X: Lecture #10
30
Object Deletion – Approach 1
int delIdx = 1;
A
person
person
0
A
Delete Person B by
setting the reference in
position 1 to null.
person[delIdx] = null;
1
B
2
C
3
D
Before A is executed
CS1101X: Lecture #10
0
A
1
2
C
3
D
After A is executed
31
Object Deletion – Approach 2
int delIdx = 1, last = 3;
person[delIndex] = person[last];
A
person[last--]
person
= null;
person
0
A
Delete Person B by
setting the reference in
position 1 to the last
person.
1
B
2
C
3
D
Before A is executed
CS1101X: Lecture #10
0
A
1
D
2
3
C
After A is executed
32
Person Array Processing – Sample 3

Searching for a particular person. Approach 2 Deletion is
used.
int i = 0;
while ( person[i] != null && !person[i].getName().equals("Latte") ) {
i++;
}
if ( person[i] == null ) {
// not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");
} else {
// found - successful search
System.out.println("Found Ms. Latte at position " + i);
}
CS1101X: Lecture #10
33
Passing Arrays to Methods (1/6)

How do we write a method that accepts an array as its
parameter, and how do we invoke such a method?

The method to sum the values in an integer list:
public static int sumList(int[] list) {
int sum = 0;
for (int i = 0; i < list.length; ++i) {
sum += list[i];
}
return sum;
}
CS1101X: Lecture #10
34
Passing Arrays to Methods (2/6)

The invocation of the sumList() method:
public static void main(String[] args) {
int[] aList = { 2, 6, 4 };
int answer = sumList(aList);
System.out.println("Sum of list is "
+ answer);
}

Output:
Sum of list is 12
CS1101X: Lecture #10
35
Passing Arrays to Methods (3/6)
Code
A
public int searchMinimum(float[] number))
{
minOne
= searchMinimum(arrayOne);
…
}
At
A before searchMinimum
arrayOne
A. Local variable
number does not
exist before the
method execution
State of
Memory
CS1101X: Lecture #10
36
Passing Arrays to Methods (4/6)
Code
public int searchMinimum(float[] number))
{
B
minOne
= searchMinimum(arrayOne);
…
}
The address is copied at B
arrayOne
number
B. The value of the
argument, which is
an address, is copied
to the parameter.
State of
Memory
CS1101X: Lecture #10
37
Passing Arrays to Methods (5/6)
Code
public int searchMinimum(float[] number))
{
minOne
= searchMinimum(arrayOne);
…
C
}
While at C
arrayOne
inside the method
number
C. The array is
accessed via
number inside
the method.
State of
Memory
CS1101X: Lecture #10
38
Passing Arrays to Methods (6/6)
Code
public int searchMinimum(float[] number))
{
minOne
= searchMinimum(arrayOne);
D
…
}
At D after searchMinimum
arrayOne
number
D. The parameter is
erased. The argument
still points to the same
object.
State of
Memory
CS1101X: Lecture #10
39
Passing Array Elements to Methods (1/2)

How do we write a method that accepts an array element
as its parameter, and how do we invoke such a method?

The method to sum two values in an integer list:
public static int sumTwoElements(int a,
int b) {
return a + b;
}

No difference from a method that adds two integer values.
CS1101X: Lecture #10
40
Passing Array Elements to Methods (2/2)

The invocation of the sumTwoElements() method:
public static void main(String[] args) {
int[] aList = { 2, 6, 4 };
int answer = sumTwoElements(aList[0],
aList[2]);
System.out.println("Sum is " + answer);
}

Output:
Sum is 6
CS1101X: Lecture #10
41
Two-Dimensional Arrays

Two-dimensional arrays are useful in representing tabular
information.
CS1101X: Lecture #10
42
Declaring and Creating a 2D Array
Declaration
<data type> [][] <variable>
<data type>
<variable>[][]
//variation 1
//variation 2
Creation
<variable>
= new <data type> [ <size1> ][ <size2> ]
Example
payScaleTable
0
double[][] payScaleTable;
0
payScaleTable
1
= new double[4][5];
1
2
3
4
2
3
CS1101X: Lecture #10
43
Accessing an Element

An element in a two-dimensional array is
accessed by its row and column index.
CS1101X: Lecture #10
44
Sample 2D Array Processing

Find the average of each row.
double[ ] average = { 0.0, 0.0, 0.0, 0.0 };
for (int i = 0; i < payScaleTable.length; i++) {
for (int j = 0; j < payScaleTable[i].length; j++) {
average[i] += payScaleTable[i][j];
}
average[i] = average[i] / payScaleTable[i].length;
}
CS1101X: Lecture #10
45
Java Implementation of 2D Arrays
 The
sample array creation
payScaleTable = new double[4][5];
is really a shorthand for
payScaleTable = new double [4][ ];
payScaleTable[0]
payScaleTable[1]
payScaleTable[2]
payScaleTable[3]
CS1101X: Lecture #10
=
=
=
=
new
new
new
new
double
double
double
double
[5];
[5];
[5];
[5];
46
Two-Dimensional Arrays


Subarrays may be different lengths.
Executing
triangularArray = new double[4][ ];
for (int i = 0; i < 4; i++)
triangularArray[i] = new double [i + 1];
results in an array that looks like:
CS1101X: Lecture #10
47
Example #1 (1/2)

Segment
int[][] m = new int[3][];
m[0] = new int[4];
m[1] = new int[4];
m[2] = new int[4];

Produces
m[0] m[1] m[2]
m[2][0] m[2][1] m[2][2] m[2][3]
m
0
0
0
0
m[0][0] m[0][1] m[0][2] m[0][3]
CS1101X: Lecture #10
0
0
0
0
0
0
0
0
m[1][0] m[1][1] m[1][2] m[1][3]
48
Example #1 (2/2)

Segment
for (int r = 0; r < m.length; ++r) {
for (int c = 0; c < m[r].length; ++c) {
System.out.print("Enter a value: ");
m[r][c] = scanner.nextInt();
}
}
What does this code do?
CS1101X: Lecture #10
49
Example #2

Segment
String[][]
s[0] = new
s[1] = new
s[2] = new
s[3] = new

s = new String[4][];
String[2];
String[2];
String[4];
String[3]
Produces
s[0]
s[1]
s[2]
s[3]
s
s[3][0] s[3][1] s[3][2]
null null null
null null
null null
s[0][0] s[0][1]
s[1][0] s[1][1]
CS1101X: Lecture #10
null null null null
s[2][0] s[2][1] s[2][2] s[2][3]
50
Example #3

Segment
int[][] c = { {1, 2}, {8, 9}, {3, 8},
{12, 1, 7} };

Produces
c[0]
c[1]
c[2]
c[3]
c[3][0] c[3][1] c[3][2]
c
1
2
c[0][0] c[0][1]
CS1101X: Lecture #10
8
9
c[1][0] c[1][1]
12
1
3
8
7
s[2][0] s[2][1]
51
Methods with Multi-dimensional Arrays

Method zero() sets to 0 all of the elements of the
subarrays of its int[][] parameter array a.
public void zero(int[][] a) {
for (int r = 0; r < a.length; ++r)
for (int c = 0; c < a[r].length; ++c)
a[r][c] = 0;
}
CS1101X: Lecture #10
52
Matrices


A two-dimensional array is sometimes known as a
matrix because it resembles that mathematical
concept.
A matrix a with m rows and n columns is represented
mathematically in the following manner.
a1  1 a 1 2  a 1 n
a2  1 a 2 2  a 2 n


am  1 a m 2  a m n
CS1101X: Lecture #10
53
Matrix Addition (1/2)

Definition C = A + B
 ci,j
= ai,j + bi,j
1 2 0
 1 0 0 




0 1 1   2 1 0 
1 0 1
 0 2  1




CS1101X: Lecture #10
 0 2 0


  2 2 1
 1 2 0


54
Matrix Addition (2/2)
public static double[][] add(double[][] a, double[][] b) {
// determine number of rows in solution
int m = a.length;
// determine number of columns in solution
int n = a[0].length;
// create the array to hold the sum
double[][] c = new double[m][n];
// compute the matrix sum row by row
for (int i = 0; i < m; ++i) {
// produce the current row
for (int j = 0; j < n; ++j) {
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
CS1101X: Lecture #10
55
Matrix Multiplication

Definition C = A * B
 ci,j
= (ai,1  b1,j ) + (ai,2  b2,j ) + . . . + (ai,n  bn,j )
 ci,j
is sum of terms produced by multiplying the
elements of A’s row i with B’s column j.
1 2 0
 1 0 0 




0 1 1   2 1 0 
1 0 1
 0 2  1




CS1101X: Lecture #10
3 2 0


  2 3  1
  1 2  1


56
List



The java.util standard package contains different
types of classes for maintaining a collection of
objects.
These classes are collectively referred to as the
Java Collection Framework (JCF).
JCF includes classes that maintain collections of
objects as sets, lists, or maps.
CS1101X: Lecture #10
57
Java Interface

A Java interface defines only the behavior of
objects



It includes only public methods with no method bodies.
It does not include any data members except public
constants
No instances of a Java interface can be created
CS1101X: Lecture #10
58
Collections Framework

Limitations of arrays
 Cannot
be resized
 There are no operations that support insertion of new
elements or deletion of existing elements.

Collections framework
 A rich
set of list representations and algorithms.
 Interface is java.util.AbstractCollection.
CS1101X: Lecture #10
59
JCF Lists

JCF includes the List interface that supports
methods to maintain a collection of objects as
a linear list
L = (l0, l1, l2, . . . , lN)


We can add to, remove from, and retrieve
objects in a given list.
A list does not have a set limit to the number
of objects we can add to it.
CS1101X: Lecture #10
60
List Methods

Here are five of the 25 list methods:
boolean add
( Object o )
Adds an object o to the list
void
clear
(
)
Clears this list, i.e., make the list empty
Object
get
( int idx
)
Returns the element at position idx
boolean remove ( int idx
)
Removes the element at position idx
int
size
(
)
Returns the number of elements in the list
CS1101X: Lecture #10
61
Using Lists
 To
use a list in a program, we must create an
instance of a class that implements the List
interface.
 Two classes that implement the List interface:


ArrayList
LinkedList
 The
ArrayList class uses an array to manage
data.
 The LinkedList class uses a technique called
linked-node representation.
CS1101X: Lecture #10
62
Sample List Usage

Here's an example of manipulating a list:
import java.util.*;
List
friends;
Person
person;
friends = new ArrayList( );
person = new Person("jane", 10, 'F');
friends.add( person );
person = new Person("jack",
6, 'M');
friends.add( person );
Person p = (Person) friends.get( 1 );
CS1101X: Lecture #10
63
Class ArrayList (1/5)

ArrayList provides a resizeable list representation that
implements the List interface.
ArrayList c = new ArrayList();
ArrayList d = new ArrayList(20);



Variable c references a new ArrayList that can represent up to 10
elements before it will need to update its internal capacity.
Variable d can represent up to 20 elements before it will need to
update its capacity.
Refer to API specification.
CS1101X: Lecture #10
64
Class ArrayList (2/5)

Adding elements:
c.add("Brooklyn");
c.add("Wichita Falls");
ArrayList
c
"Brooklyn"
CS1101X: Lecture #10
"Wichita Fall"
65
Class ArrayList (3/5)

Adding elements:
for (int i = 0; i < 3; ++i) {
d.add(new Integer(i));
}
ArrayList
d
CS1101X: Lecture #10
Integer
Integer
Integer
0
1
2
66
Class ArrayList (4/5)

Method get() to access elements of an ArrayList.
public static void displayList(ArrayList a) {
for (int i = 0; i < a.size(); ++i)
System.out.println(a.get(i));
}

Invocation (assuming that class is DemoArrayList):
DemoArrayList.displayList(c);

Output:
Brooklyn
Witchita Falls
CS1101X: Lecture #10
67
Class ArrayList (5/5)

Method set() to change the value of an element in an
ArrayList.
c.set(1, "Glen Rock");
DemoArrayList.displayList(c);

Output:
Brooklyn
Glen Rock
CS1101X: Lecture #10
68
Iterator (1/2)

A very common process is examining every element in a
collection. The ArrayList class provides a special way to
iterate over its elements.




The iterator() method of ArrayList returns an Iterator object.
Iterator interface is defined in the java.util package.
Need to import java.util.Iterator.
Methods provided in Iterator:

boolean hasNext()
Returns whether this Collection has more elements to return.

Object next()
Returns next element of this Collection. If there is no next element, it
throws a NoSuchElementException.

void remove()
Remove from this Collection the last element returned by the iterator.
CS1101X: Lecture #10
69
Iterator (2/2)
import java.util.ArrayList;
import java.util.Iterator;
public class DemoList {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(12));
list.add(new Integer(7));
list.add(new Integer(-98));
for (int i = 0; i < list.size(); ++i) {
System.out.println(list.get(i));
}
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Same
output:
12
7
-98
}
}
CS1101X: Lecture #10
70
Collections Algorithms (1/3)

A collection of algorithms for performing standard list
operations.



Algorithms are implemented as class methods of the class
java.util.Collections.
Several methods make use of interfaces java.lang.Comparable
or java.util.Comparator.
public int compareTo(Object v)
Returns a negative value if this object is less than v; returns zero if
the two objects are equal; and returns a positive value otherwise.

public int compare(Object v1, Object v2)
Returns a negative value if v1 is less than v2; returns zero if the two
values are equal; and returns a positive value otherwise.

public boolean equals(Object v)
Returns true or false, whether v is equal to this object.
CS1101X: Lecture #10
71
Collections Algorithms (2/3)
import java.util.*;
public class DemoCollections {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < 10; ++i)
a.add(new Integer(i));
System.out.println("Original: " + a);
Collections.reverse(a);
System.out.println("Reversed: " + a);
Collections.shuffle(a);
System.out.println("Shuffled: " + a);
Collections.sort(a);
System.out.println("Sorted:
" + a);
}
}
CS1101X: Lecture #10
72
Collections Algorithms (3/3)
Output:
Original:
Reversed:
Shuffled:
Sorted:
CS1101X: Lecture #10
[0,
[9,
[3,
[0,
1,
8,
0,
1,
2,
7,
1,
2,
3,
6,
9,
3,
4,
5,
5,
4,
5,
4,
2,
5,
6,
3,
8,
6,
7,
2,
6,
7,
8,
1,
7,
8,
9]
0]
4]
9]
73
End of Lecture #10
CS1101X: Lecture #10
74