Title: Arrays
1Arrays
- Chapter 8
- Fall 2005
- CS 101
- Aaron Bloomfield
2Introduction to arrays
3Background
- Programmer often need the ability to represent a
group of values as a list - List may be one-dimensional or multidimensional
- Java provides arrays and the collection classes
- The Vector class is an example of a collection
class - Consider arrays first
4Example
- Definitions
- char c
- int value new int10
- Causes
- Array object variable c is un-initialized
- Array object variable v references a new ten
element list of integers - Each of the integers is default initialized to 0
5An array example
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
int v new int10 int i 7 int j 2 int
k 4 v0 1 vi 5 vj vi
3 vj1 vi v0 vvj
12 System.out.println(v2) vk
stdin.nextInt()
8 is displayed
Suppose 3 is extracted
6Array variable definition styles
int a int a
7Array variable definition styles
8Where weve seen arrays
- public static void main (String args)
- Thus, the main() method takes in a String array
as the parameter - Note that you can also define it as
- public static void main (String args)
9Basic terminology
- List is composed of elements
- Elements in a list have a common name
- Example a3 5
- The common name is a
- The list as a whole is referenced through the
common name - List elements are of the same type the base
type - Elements of a list are referenced by subscripting
(indexing) the common name
10Java array features
- Subscripts are denoted as expressions within
brackets - Base (element) type can be any type
- Size of array can be specified at run time
- This is different that pure C! (for the most
part, at least) - Index type is integer and the index range must be
0 ... n-1 - Where n is the number of elements
- Just like Strings indexing!
- 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
- More on this later
11Consider
- Segment
- int b new int100
- b-1 0
- b100 0
- Causes
- Array variable to reference a new list of 100
integers - Each element is initialized to 0
- Two exceptions to be thrown
- -1 is not a valid index too small
- 100 is not a valid index too large
- IndexOutOfBoundsException
12Consider
- Point p new Point3
- p0 new Point(0, 0)
- p1 new Point(1, 1)
- p2 new Point(2, 2)
- p0.setX(1)
- p1.setY(p2.getY())
- Point vertex new Point(4,4)
- p1 p0
- p2 vertex
- Point p new Point3
- p0 new Point(0, 0)
- p1 new Point(1, 1)
- p2 new Point(2, 2)
- p0.setX(1)
- p1.setY(p2.getY())
- Point vertex new Point(4,4)
- p1 p0
- p2 vertex
13Todays demotivators
14Explicit initialization
ElementType
id
exp
,
exp
,
...
exp
0
1
-1
n
15Explicit initialization
- Example
- String puppy pika, arlo, schuyler",
nikki" - int unit 1
- Equivalent to
- String puppy new String4
- puppy0 pika" puppy1 arlo"
- puppy2 schuyler" puppy3 nikki"
- int unit new int1
- unit0 1
16Array members
- Member length
- Size of the array
- for (int i 0 i lt puppy.length i)
- System.out.println(puppyi)
-
17Array members
- Member clone()
- Produces a shallow copy
- Point u new Point(0, 0), new Point(1, 1)
- Point v u.clone()
- v1 new Point(4, 30)
- Point u new Point(0, 0), new Point(1, 1)
- Point v u.clone()
- v1 new Point(4, 30)
18Array members
- Member clone()
- Produces a shallow copy
- Point u new Point(0, 0), new Point(1, 1)
- Point v u.clone()
- v1.setX(10)
- Point u new Point(0, 0), new Point(1, 1)
- Point v u.clone()
- v1.setX(10)
19Making a deep copy
- We want to copy the array and all the objects
each element of the array references - This is called a deep copy
- Example
- Point w new Pointu.length
- for (int i 0 i lt u.length i)
- wi (Point) ui.clone()
-
20Making a deep copy
21Review of arrays
- Creating an array
- int foo new int10
- Accessing an array
- foo3 7
- System.out.print (foo1)
- Creating an array
- String bar new String10
- Accessing an array
- bar3 qux
- System.out.println (bar1)
22How Java represents arrays
- Consider
- int a 1, 2, 3, 4, 5
a
23More about how Java represents Arrays
- Consider
- int a
- int b null
- int c new int5
- int d 1, 2, 3, 4, 5
- a c
- d c
- int a
- int b null
- int c new int5
- int d 1, 2, 3, 4, 5
- a c
- d c
-
24Fan-supplied demotivators!
25ArrayTools
26ArrayTools.java
- We want to create a series of general utility
methods to be used for arrays - We will put these into an ArrayTools class
27ArrayTools.java outline
- public class ArrayTools
- // class constant
- private static final int MAX_LIST_SIZE 1000
- // sequentialSearch() examine unsorted list
for key - public static int sequentialSearch(int
data, int key) ... - // putList () prints list to screen
- public static void putList(int data) ...
- // getList() extract and return up to
MAX_LIST_SIZE values - public static int getList() ...
- // reverse() reverses the order of the element
values - public static void reverse(int list) ...
- // binarySearch() examine sorted list for a
key
28ArrayTools.java method putList()
- To print the array
- public static void putList(int data)
- for (int i 0 i lt data.length i)
- System.out.println(datai)
-
-
- Consider
- int score 6, 9, 82, 11, 29, 85, 11, 28, 91
- putList(score)
29ArrayTools.java method getList()
- public static int getList()
- Scanner stdin new Scanner (System.in)
- int buffer new intMAX_LIST_SIZE
- int listSize 0
- for (int i 0 (i lt MAX_LIST_SIZE)
- stdin.hasNext() i)
- bufferi stdin.nextInt()
- listSize
-
- int data new intlistSize
- for (int i 0 i lt listSize i)
- datai bufferi
-
- return data
-
30End of lecture on 7 Nov 2005
31ArrayTools.java method reverse()
- public static void reverse(int data)
- int clone data.clone()
- for ( int i 0 i lt clone.length i )
- datai cloneclone.length-1-i
-
-
- Consider
- int foo 1, 2, 3, 4, 5
- reverse (foo)
- putList (foo)
32Demo.java
- public class Demo
- // main() application entry point
- public static void main(String args)
- System.out.println ("")
- System.out.println ("Enter list of integers")
- int numbers ArrayTools.getList ()
- System.out.println ("")
- System.out.println ("Your list")
- ArrayTools.putList (numbers)
- ArrayTools.reverse (numbers)
- System.out.println ("")
- System.out.println ("Your list in reverse")
- ArrayTools.putList (numbers)
- System.out.println ()
-
33(No Transcript)
34ArrayTools demo
35 main (String args)
36Consider that main() method again
- public static void main (String args)
- How does one pass in a parameter to the main
method? - public class MainParameters
- public static void main (String args)
- System.out.println ("Number of paramters to
"main() " args.length) - if ( args.length gt 0 )
- for ( int i 0 i lt args.length i )
- System.out.println ("parameter "
- i " '" argsi "'")
-
-
37Program Demo
- MainParameters.java
- Via JCreator
- Via the command line
38Basic array searching
39Searching for a value
- System.out.println("Enter search value (number)
") - int key stdin.nextInt()
- int i
- for (i 0 i lt data.length i)
- if (key datai)
- break
-
-
- if (i ! data.length)
- System.out.println(key " is the " i "-th
element") -
- else
- System.out.println(key " is not in the list")
i
System.out.println("Enter search value (number)
") int key stdin.nextInt() int i if (key
datai) break if (i ! data.length)
System.out.println(key " is the " i
"-th element")
i lt data.length
i 0
40Searching for the minimum value
- Segment
- int minimumSoFar sample0
- for (int i 1 i lt sample.length i)
- if (samplei lt minimumSoFar)
- minimumSoFar samplei
-
41ArrayTools.java method sequentialSearch()
- public static int sequentialSearch(int data,
int key) - for (int i 0 i lt data.length i)
- if (datai key)
- return i
-
-
-
- return -1
-
- Consider
- int score 6, 9, 82, 11, 29, 85, 11, 28, 91
- int i1 sequentialSearch(score, 11)
- int i2 sequentialSearch(score, 30)
42Todays demotivators
43Sorting
44Sorting
- Problem
- Arranging elements so that they are ordered
according to some desired scheme - Standard is non-decreasing order
- Why don't we say increasing order?
- Major tasks
- Comparisons of elements
- Updates or element movement
45Selection sorting
- Algorithm basis
- On iteration i, a selection sorting method
- Finds the element containing the ith smallest
value of its list v and exchanges that element
with vi - Example iteration 0
- Swaps smallest element with v0
- This results in smallest element being in the
correct place for a sorted result
46Selection sorting
- Algorithm basis
- On iteration i, a selection sorting method
- Finds the element containing the ith smallest
value of its list v and exchanges that element
with vi - Example iteration 1
- Swaps second smallest element with v1
- This results in second smallest element being in
the correct place for a sorted result
47Selection sorting
- Algorithm basis
- On iteration i, a selection sorting method
- Finds the element containing the ith smallest
value of its list v and exchanges that element
with vi - Example iteration 2
- Swaps third smallest element with v2
- This results in third smallest element being in
the correct place for a sorted result
48Selection sorting
- Algorithm basis
- On iteration i, a selection sorting method
- Finds the element containing the ith smallest
value of its list v and exchanges that element
with vi - Example iteration 3
- Swaps fourth smallest element with v3
- This results in fourth smallest element being in
the correct place for a sorted result
49Selection sorting
- Algorithm basis
- On iteration i, a selection sorting method
- Finds the element containing the ith smallest
value of its list v and exchanges that element
with vi - Example iteration 4
- Swaps fifth smallest element with v4
- This results in fifth smallest element being in
the correct place for a sorted result
50ArrayTools.java selection sorting
- public static void selectionSort(int v)
- for (int i 0 i lt v.length-1 i)
- // find the location of the ith smallest
element - int spot i
- for (int j i1 j lt v.length j)
- if (vj lt vspot) // is current location
ok? - // update spot to index of smaller
element - spot j
-
-
- // spot is now correct, so swap elements
- int rmbr vi
- vi vspot
- vspot rmbr
-
51Iteration i
- // find the location of the ith smallest element
- int spot i
- for (int j i1 j lt v.length j)
- if (vj lt vspot) // is spot ok?
- // update spot with index of smaller element
- spot j
-
- // spot is now correct, swap elements vspot and
vi
52Todays demotivators
53Binary search
54Binary search
- Given a list, find a specific element in the list
- List MUST be sorted!
- Each time it iterates through, it cuts the search
space in half - A binary search is MUCH faster than a sequential
search
55Binary search use
- The BS in BSDemo is for Binary Search, mind you
- public class BSDemo
- public static void main(String args)
- int numbers 9, 3, 1, 8, 4, 6, 10, 2
- System.out.println ("The original list of
numbers") - ArrayTools.putList(numbers)
- System.out.println()
-
- ArrayTools.selectionSort(numbers)
- System.out.println ("The sorted list of
numbers") - ArrayTools.putList(numbers)
- System.out.println()
-
- System.out.println ("Searching for 0 "
ArrayTools.binarySearch(numbers, 0)) - System.out.println ("Searching for 1 "
ArrayTools.binarySearch(numbers, 1)) - System.out.println ("Searching for 4 "
ArrayTools.binarySearch(numbers, 4)) - System.out.println ("Searching for 5 "
ArrayTools.binarySearch(numbers, 5))
56Binary search use demo
57Binary search
- public static int binarySearch (int data, int
key) - int i 0 // left endpoint of
search interval - int j data.length-1 // right endpoint of
search interval - while ( i lt j )
- int m (ij)/2
- if ( key gt datam )
- i m1
- else
- j m
-
-
- if ( key datai )
- return i
- else
- return -1
-
58Binary search, take 1
public static int binarySearch (int data, int
key)
if ( key datai ) return i else
return -1
if ( key datai ) return i else
return -1
int i 0 int j data.length-1
int i 0 int j data.length-1
while ( i lt j ) int m (ij)/2 if ( key gt
datam ) i m1 else j m
while ( i lt j ) int m (ij)/2 if ( key gt
datam ) i m1 else j m
a0 a1 a2 a3 a4 a5 a6 a7 a8 a9
2 4 6 8 10 12 14 16 18 20
data
0
9
4
5
7
7
6
6
5
6
59Binary search
- But what if the element is not in the list?
60Binary search, take 2
public static int binarySearch (int data, int
key)
if ( key datai ) return i else
return -1
if ( key datai ) return i else
return -1
int i 0 int j data.length-1
int i 0 int j data.length-1
while ( i lt j ) int m (ij)/2 if ( key gt
datam ) i m1 else j m
while ( i lt j ) int m (ij)/2 if ( key gt
datam ) i m1 else j m
a0 a1 a2 a3 a4 a5 a6 a7 a8 a9
2 4 6 8 10 12 14 16 18 20
data
0
9
4
5
7
7
6
7
61Binary search
- A somewhat alternative view of what a binary
search does
62How long does a binary search take?
- Given a array of 64 elements
- 1st iteration cuts the array to 32
- 2nd iteration cuts the array to 16
- 3rd to 8
- 4th to 4
- 5th to 2
- 6th to 1
- Given a array of 1024 elements
- 1st iteration cuts the array to 512
- ...
- 10th iteration cuts the list to 1 element
- Thus, the binary search takes log2 n iterations!
- Where n is the size of the array
63Binary search vs. sequential search
- Assume the array has n elements
- Sequential search can take (in the worst-case) n
iterations to find the element - Binary search can take (in the worst case) log2 n
iterations to find the element - Consider a list of 1 million elements
- Binary search takes about 20 iterations
- Sequential search takes 1,000,000 iterations
- Consider a list of 1 trillion elements
- Binary search takes about 40 iterations
- Sequential search takes 1,000,000,000,000
iterations
64Demotivators
65Multi-dimensional arrays
66Multidimensional arrays
- Many problems require information be organized as
a two-dimensional or multidimensional list - Examples
- Matrices
- Graphical animation
- Economic forecast models
- Map representation
- Time studies of population change
- Microprocessor design
67Example
- Segment
- int m new int3
- m0 new int4
- m1 new int4
- m2 new int4
- Produces
When an array is created, each value is
initialized!
m
68Example
- Alternative
- int m new int34
- Produces
69Multidimensional array visualization
- A multi-dimensional array declaration (either
one) - int m new int34
- How we visualize it
or
70End of lecture on 9 November 2005
71Example
- Segment
- for (int c 0 c lt m.length c)
- for (int r 0 r lt mc.length r)
- System.out.print("Enter a value ")
- mcr stdin.nextInt()
-
72Rows by columns or columns by rows?
- Consider int m new int34
- Is that 3 rows by 4 columns or 3 columns by 4
rows? - The answer is that it can be either
- As long as you are consistent with your
column/row placement
or
73Rows by columns or columns by rows?
- This makes it 3 columns by 4 rows
- for (int c 0 c lt m.length c)
- for (int r 0 r lt mc.length r)
- System.out.print("Enter a value ")
- mcr stdin.nextInt()
-
- This makes it 3 rows by 4 columns
- for (int c 0 c lt m.length c)
- for (int r 0 r lt mc.length r)
- System.out.print("Enter a value ")
- mrc stdin.nextInt()
-
- For sake of simplicity, well always put the
column first in this course - Just like Excel
74Example
- Segment
- String s new String4
- s0 new String2
- s1 new String2
- s2 new String4
- s3 new String3
- Produces
75Multidimensional array visualization
- Segment
- String s new String4
- s0 new String2
- s1 new String2
- s2 new String4
- s3 new String3
- Produces
- Called a ragged array
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
or
0
0
0
0
0
0
76Explicit Initialization
- Segment
- int c 1, 2, 3, 4, 5, 6, 7, 8, 9
- Produces
77Matrices
- 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
78Matrix addition
- Definition C A B
- cij aij bij
- cij is sum of the elements in the same row and
column of A and B
79Matrix addition
- 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 a0.length
- // create the array to hold the sum
- double c new doublemn
- // compute the matrix sum row by row
- for (int i 0 i lt m i)
- // produce the current row
- for (int j 0 j lt n j)
- cij aij bij
-
-
80Homework J8
- You will be creating a Grid (or Map, Dungeon,
etc.) class - It will contain a 2-D array
- In each spot will be a Room object
- The Room object from the current homework
- The descriptions for the rooms will be from this
weeks lab - Can move between the rooms
- Rooms may contain a monster, weapon, etc.
81Todays demotivators
82Vector class
- This is also the review
- for the third midterm
83Limitations of arrays
- You cant change their size once created
- This can be a big problem!
- So we will create a new class that will operate
like an array - We can store and get elements by index number
- It will automatically increase in size as needed
- And other fancy features
- Lets call the class Vector
- Well see why I chose that name later
84Properties of our Vector class
- It needs to have an array to hold the values
- As our internal array will often be bigger than
the number of elements in the Vector, we need a
size as well - More on what this means in a slide or two
- Not much else
85Methods in our Vector class
- Insert and remove elements into the Vector
- Get an element from the Vector
- Find the length
- Print it out to the screen
- What happens when the array field is full, and we
want to add an element? - We will need to increase the size of the array
- So we need a method to do that as well
86Our first take on our Vector class
- public class Vector
- private Object array
- private int size 0
- Vector()
- array new Object100
-
- Vector(int length)
- array new Objectlengthfs
-
-
- What does this mean?
- Well see that a bit later
- But briefly, it means the array can store any
object
87Adding an element to our Vector
- public void add (Object o)
- arraysize o
-
- Pretty easy!
- But what if the array is full?
- We need a way to increase the capacity of the
array
88Increasing the Vectors arrays capacity
- private void increaseCapacity()
- int oldSize array.length
- Object newArray new Object2oldSize
- for ( int i 0 i lt oldSize i )
- newArrayi arrayi
- array newArray
-
- And our new add() method
- public void add (Object o)
- if ( size array.length )
- increaseCapacity()
- arraysize o
89Methods can be private as well
- Notice that the increaseCapacity() method is
called only by the add() method when necessary - Its not ever going to be called by whomever is
using our Vector - Thus, we will make it private
- That means that only other Vector methods can
call it
90Removing an element from a Vector
- public Object remove (int which)
- Object ret arraywhich
- for ( int i which i lt array.length-1 i )
- arrayi arrayi1
- arrayarray.length-1 null
- size--
- return ret
-
91Miscellaneous other methods
- public int size()
- return size
-
-
- public Object get (int which)
- return arraywhich
-
92Our toString() method
- public String toString()
- String ret ""
- for ( int i 0 i lt size i )
- ret arrayi
- if ( i ! size-1 )
- ret ", "
-
- ret ""
- return ret
-
93Using our Vector
- This code is in a separate class called
VectorUsage - public static void main (String args)
- Vector v new Vector()
- for ( int i 12 i lt 30 i )
- v.add (String.valueOf(i))
-
- System.out.println (v)
- System.out.println (v.size())
- String s (String) v.get(5)
- System.out.println (s)
- v.remove (5)
- System.out.println (v)
- v.remove (5)
- System.out.println (v)
94Program Demo
95The real Vector class
- Java provides a Vector class
- In java.util
- It contains all of the methods shown
96Program Demo
- VectorUsage.java
- But using java.util.Vector
97What about those errors?
- When compiled with java.util.Vector, we see
- Note C\...\VectorUsage.java uses unchecked or
unsafe operations. - Note Recompile with -Xlintunchecked for
details. - You can ignore these
- They deal with generics, which you will see in
future courses - The program was still compiled
98More on using the Vector class
- To add a Room object r to the end of a Vector v
- v.add(r)
- To get the Room object at the end of the Vector v
- Room r (Room) v.get(v.size()-1)
- To remove a Room object from the end of a Vector
v - Room r (Room) v.remove(v.size()-1)
- This both removes the object from the Vector and
stores the removed value into r
99New demotivators!!!
100Wrapper classes
101But what about adding variables?
- The add method takes an Object as a parameter
- public void add (Object o)
- Although we havent seen it yet, this means you
can add any object you want to the vector - Primitive types (i.e. variables) are not objects
- How can they be added?
- The solution wrapper classes!
102The Integer wrapper class
- This is how you add an int variable to a Vector
- int x 5
- Integer i new Integer(x)
- vector.add (i)
- //
- Integer j (Integer) v.get(0)
- var y j.intValue()
- Pretty annoying syntax well see how to get
around it in a bit
103More on wrapper classes
- All the primitive types have wrapper classes
- Usually, the names are just the capitalized
version of the type - I.e. Double for double, Byte for byte, etc.
- Two exceptions int and char
- int has Integer
- char has Character
104End of lecture on 14 November 2005
- The slides on wrapper classes were copied to the
slide set for chapter 7
105More on wrapper classes
- Consider this code
- int x 5
- vector.add (x)
- //
- int y vector.get(0)
- Does this code work?
- It shouldnt
- As we are adding a variable (not an object) to a
vector - But it does work!
- Why?
106Auto-boxing
- Java 1.5 will automatically wrap a primitive
value into its wrapper class when needed - And automatically unwrap a wrapper object into
the primitive value - So Java translates the previous code into the
following - int x 5
- vector.add (new Integer(x))
- //
- int y ((Integer)vector.get(0)).intValue()
- This is called autoboxing
- And auto-unboxing (unauto-boxing?)
- This does not work in Java 1.4 or before
107More on auto-boxing
- Consider the following code
- Double d 7.5
- Double e 6.5
- Double f d e
- System.println (f)
- This is doing a lot of auto-boxing (and
auto-unboxing) - Double d new Double(7.5)
- Double e new Double(6.5)
- Double f newDouble(d.doubleValue()
e.doubleValue()) - System.println (f)