Two possibilities:
A)
int
[] scores, totals, results;
B) int scores [], totals, results;
Which declaration above declares scores, totals and results as arrays?
scores = new int[5];
int [] scores = new int[10];
for (int x = 0; x < 10; x++)
scores[x] = x * 10;
int [] scores = {98, 66, 76, 83, 89, 70, 60, 82, 79, 84};
index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
scores |
98 |
66 |
76 |
83 |
89 |
70 |
60 |
82 |
79 |
84 |
Each element
in the array stores a single occurrence of that data type (a primitive type or
object).
An array
element can be used wherever that type of element can be used.
In order to access the 5th
element in an array, it is not necessary to “read” through the first 4.
An element can be accessed
“randomly” by using the array name and the index number of the element.
int x = 4;
System.out.print(
“ “ + scores[4]);
int total = scores[1] + scores[x];
Are the following references
valid?
System.out.print( “ “ +
scores[-2]);
int total = scores[1] + scores[10];
The array name is a reference
variable. Reference variables can be
passed as a parameter.
Sorts.insertionSort(scores);
The number of elements in the
array can be obtained from the length value
int howBig = scores.length;
The length value is frequently
used to control looping.
int sum = 0;
for (int x = 0;
x < scores.length; x++)
sum += scores[x];
Two
dimensional array (each row has the same number of columns)
int[][] scores = new int[4][10];
for (int row=0; row < scores.length; row++)
for (int
col=0; col < scores[row].length; col++)
scores[row][col] = row * 10 + col;
Two
dimensional array (each row has a different number of columns) – variable
length array
int [][] scores;
scores = new int[4][];
scores [0] = new int [10];
scores [1] = new int [20];
scores [2] = new int [30];
scores [3] = new int [40];
. . .
int max = 0;
for (int row = 0; i <
scores.length; row++)
for (int col = 0; col < scores[row].length; col++)
if (scores[row][col] > max)
max = scores [row][col];
int [][][] table = new int[5][6][7]; . . . int a,b,c, max = 0; for (a = 0; a < table.length; a++) for (b = 0; b <
table[a].length; b++) for (c = 0; c <
table[a][b].length; c++) if
(table[a][b][c] > max) max = table
[a][b][c]; |
Array methods are available in System and in java.util.Arrays
Method
|
Result |
System.arraycopy(array1,startA1,array2,startA2,number) |
Copies
number of components from position startA1 in array array1 to
startA2 in array array2 |
(type
[]) array.clone(); |
Creates
a copy of array elements and values |
array1
= array2; |
array1
becomes an alias of array2 |
array1
== array2; |
tests
wither array1 and array2 point to the same array |
Arrays.equals(array1,array2); |
Returns
true if the arrays are equal in the number of components and
values |
Arrays.fill(array,
value); |
All
the components in array get the same value |
Arrays.fill(array,
start, stop, value); |
Components
from start to stop get the same value; |
Arrays.sort(array); |
Components
are sorted in ascending order |
Arrays.sort(array,
start, stop); |
Components
from start to stop are sorted in ascending order |
Arrays.binarySearch(array,
value); |
Searches
for component with a given value. If
found, this returns the index of the array.
If not found, this returns a –1; |
Sample Program using java.util.Arrays
import java.util.Arrays;
public class ArrayTest{
public static void main(String[] args) {
int [] array1 = {27, 32, 55};
int [] array2 = (int []) array1.clone();
compareMemorySpaces(array1, "Array1", array2,
"Array2");
compareArrayContent(array1,"Array1", array2,
"Array2");
printBothArrays(array1, "Array1", array2, "Array2");
array1[0] = 50;
compareArrayContent(array1,"Array1", array2,
"Array2");
printBothArrays(array1, "Array1", array2, "Array2");
int [] array3 = new int [3];
array3 = array1; //
array3 now points to array1
compareMemorySpaces(array1, "Array1", array3,
"Array3");
compareArrayContent(array1,"Array1", array3,
"Array3");
printBothArrays(array1, "Array1", array3, "Array3");
array1[0] = 11;
compareArrayContent(array1, "Array1", array3,
"Array3");
printBothArrays(array1,"Array1", array3, "Array3");
int [] array4 = {1,2,3};
printArray(array4, "Array4");
System.arraycopy(array1,1,array4,0,2);
printBothArrays(array1, "Array1", array4, "Array4");
}
private static void printBothArrays(int first[], String firstName,
int second[], String
secondName) {
System.out.println("Index\t" + firstName +
"\t" + secondName);
int smaller = (first.length > second.length) ?
second.length : first.length;
for (int x = 0; x <
smaller; x++)
System.out.println(" " + x + "\t
" + first[x] + "\t
" + second[x]);
System.out.println("");
}
private static void compareMemorySpaces(int [] first,
String firstName,
int [] second,
String secondName) {
System.out.print(firstName + " and " +
secondName);
if (first == second)
System.out.println(" point to the SAME memory
space");
else
System.out.println(" point to DIFFERENT memory
spaces");
}
private static void compareArrayContent(int first [], String firstName,
int second [], String secondName) {
System.out.print(firstName + " and " + secondName
+ " ");
if (Arrays.equals(first,second))
System.out.println("have the
SAME values");
else
System.out.println("have DIFFERENT values");
}
private static void printArray(int any [], String anyName) {
System.out.println("Index\t" + anyName );
for (int x = 0; x < any.length; x++)
System.out.println(" " + x + "\t
" + any[x]);
System.out.println("");
}
}
public class Sorts
{
public
static void selectionSort (int[] numbers)
{
int min,
temp;
for (int
index = 0; index < numbers.length-1; index++)
{
min =
index;
for
(int scan = index+1; scan < numbers.length; scan++)
if (numbers[scan] < numbers[min])
min = scan;
// swap
values
temp = numbers[min];
numbers[min] = numbers[index];
numbers[index] = temp;
}
}
public
static void insertionSort (int[] numbers)
{
for (int
index = 1; index < numbers.length; index++)
{
int
key = numbers[index];
int
position = index;
// shift
larger values to the right
while
(position > 0 && numbers[position-1] > key)
{
numbers[position] = numbers[position-1];
position--;
}
numbers[position] = key;
}
}
public
static void insertionSort (Comparable[] objects)
{
for (int
index = 1; index < objects.length; index++)
{
Comparable key = objects[index];
int position
= index;
//
shift larger values to the right
while
(position > 0
&&
objects[position-1].compareTo(key) > 0)
{
objects[position] = objects[position-1];
position--;
}
objects[position] = key;
}
}
}
public class SortScores
{
public
static void main (String[] args)
{
String[]
grades = {"A", "A-", "B+", "B",
"B-", "C+", "C", "C-",
"D+", "D",
"D-", "F"};
int[]
cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0};
int[]
scores = {89, 94, 69, 80, 97, 85, 73, 91, 77, 85, 93};
System.out.println("Grades in random order are:");
for
(int x = 0; x < scores.length; x++)
for (int r = 0; r < cutoff.length; r++)
if (scores[x] >= cutoff[r]) {
System.out.println (scores[x] + " = " + grades[r]);
break;
}
Sorts.selectionSort (scores);
System.out.println("\nGrades from high to low are:");
for
(int r = 0,x = scores.length-1; x > 0; x--)
{
while (scores[x] < cutoff[r]) r++;
System.out.println (scores[x] + " = " + grades[r]);
}
}
}
What needs to be modified in this program to sort the grades
array?
What needs to be modified to sort the grades array correctly?
Sorting Objects and the Comparable Interface
The Comparable
Interface is needed to have a generic sort for a set of objects.
In order to implement
the interface, the object should have the key phrase
implements Comparable
The object doing the
implementation should also have the following method
int compareTo (Object obj)
// postcondition:
// returns an integer that is less than,
// equal to, or greater than zero if the
// executing object is less than, equal to,
// or greater than the parameter obj;
Drawbacks of Arrays
Programming complexity is
increased because:
·
Space
for the entire array must be allocated before any elements can be stored.
Too
much space, is overhead to the system but it does not contain useful
information.
·
The
programmer must provide all the code for operating the array.
Inserting and deleting requires programming
subroutines or procedures
Vector – an array-based class in the java.util package.
·
Stores
object references (the objects can be of any type)
·
Dynamically
grows or shrinks as needed
·
Insertion
and deletion only require a single method invocation
Vector
Interface |
Array
Operations (will these work?) |
Vector
group = new Vector(); // do
not have to specify size |
String
[] group = new String[4]; //
must give initial capacity |
group.addElement
("Larry"); group.addElement
("Curly"); group.addElement
("Moe"); //
adds to end of array |
group[0]
= “Larry”; group[1]
= “Curly”; group[2]
= “Moe”; //
must specify storage location |
group.capacity() |
group.length |
group.size() //
number of elements stored |
int
numberUsed = 0, x = 0; while
(group[x++] != null); numberUsed
= x; //
gets number elements used |
group.insertElementAt("John",
1); |
// if
there is enough room in the array //
just shove everything back 1 for
(int x = 2; x >= 1; x--) group[x+1] = group[x]; group[1]
= "John"; //
move elements back to make room //
then move "John" at 1 |
group.insertElementAt("John",
1); |
// if
there is not enough room in the array //
create a temp then copy original to the temp //
then recopy from the temp to a larger array int
location = group.length; //
make a larger temp array String
[] temp =
new String [group.length*2]; //
copy group to temp for
(int x=0; x < group.length;x++) temp[x] = group[x]; // create larger group array String [] group = new String[temp.length]; // copy temp to group for
(int x = 0; x < temp.length; x++)
group[x] = temp[x]; //
insert group[location]
= "John"; |
group.contains("Moe") |
boolean
ans; int
x; for
(x = 0; x < group.length; x++) if (group[x].equals("Moe")) { ans = true; break; } if
(x >= group.length) ans = false; |
group.setElementAt("Abbott",1); |
group[1]
= "Abbott"; |
group.remove(0); |
for
(int x=1; x < group.length;x++) group [x – 1] = group[x]; |
group.removeElement("Curly"); |
boolean
ans; int
x, y; for
(x=0,y=0;x<group.length;x++,y++) if (group[x].equals("Curly")) break; group[y]
= null; for
(++x; x < group.length; x++,y++) group[y] = group[x]; |
group.indexOf("John"); |
int
x, index; for
(x = 0; x < group.length; x++) if (group[x].equals("John")) { index = x; break; } |
group.elementAt(2); |
group[2]; |
group.clear(); |
for
(int x=0; x < group.length;x++) group.[x] = null; |
group.isEmpty(); |
boolean
ans = true; for (int x=0; x <
group.length;x++) if (group[x] != null) { ans = false; break } |
Vectors
·
only stores object references (no primitive types – int, float,
double, etc.)
·
can simultaneously hold objects of various types -- Strings, Cash Registers, and cards can be
stored together in one Vector (use instanceof to distinguish
object references).
-- objects that contain a corresponding primitive value
Primitive Data
Type |
Wrapper Class |
Method for
Unwrapping |
boolean |
Boolean |
boolean booleanValue() |
char |
Character |
char
charValue() |
byte |
Byte |
byte
byteValue() |
short |
Short |
short
shortValue() |
int |
Integer |
int intValue() |
long |
Long |
long
longValue() |
float |
Float |
float
floatValue() |
double |
Double |
double
doubleValue() |
Wrapping and unwrapping an integer
Integer intObj; // wrapper variable for int
int x, y;
x = 5;
intObj = new Integer(x); // Puts 5 into wrapper object
y = intObj.intValue(); // gets 5 from the wrapper
Wrapping and unwrapping an integer using Vectors
import java.util.*;
public class IntWrapperVector
{
public
static void main(String [] args)
{
Vector
v = new Vector();
Integer iw;
int x,
value;
for (x
= 0; x < 20; x++)
v.addElement(new Integer(x));
for (x
= 0; x < v.size(); x++) {
iw = (Integer) v.elementAt(x);
value = iw.intValue();
System.out.println(value);
}
value
= 0;
for (x = 0; x < v.size(); x++)
value += ((Integer) v.elementAt(x)).intValue();
System.out.println("The total is " + value);
}
}