0% found this document useful (0 votes)
195 views

Arrays and Array List

The document discusses arrays and array lists in Java. It covers declaring and initializing arrays, accessing array elements, indexing arrays, reference arrays, partially filled arrays, enhanced for loops, common array algorithms like searching and sorting, and methods for manipulating arrays like copying, inserting, and removing elements. It also introduces two-dimensional arrays and how they can represent matrices.

Uploaded by

Spencer Davis
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
195 views

Arrays and Array List

The document discusses arrays and array lists in Java. It covers declaring and initializing arrays, accessing array elements, indexing arrays, reference arrays, partially filled arrays, enhanced for loops, common array algorithms like searching and sorting, and methods for manipulating arrays like copying, inserting, and removing elements. It also introduces two-dimensional arrays and how they can represent matrices.

Uploaded by

Spencer Davis
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Arrays and Array List

Cay Horstmann, “Java for Everyone”, Wiley 2010


• Declare
double[] data;
• Initialize
double[] data = new double[10];
• Declare and Initialize
double[] moreData = {32, 25, 34, 37.8, 100};
• Access
data[2] = 25.6;
System.out.println(moreData[3]);
• Indexing
– Start at 0
– Length: e.g., data.length
• Reference
int[] scores = {10, 9, 7, 4, 5};
int[] values = scores;
scores[3] = 10;
System.out.println(values[3]);
• Partially filled array
– Array is immutable: when growing
• Either make a larger one and then copy
• Or create a large one at the beginning
– Keep a companion variable to count the current size
int currentSize = 0;
Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
if (currentSize < data.length)
{
data[currentSize] = in.nextDouble();
currentSize++;
}
}
for (int i = 0; i < currentSize; i++)
{
System.out.println(data[i]);
}
• Enhanced for loop

double[] data = …
double sum = 0;

for (double element : data)


{
sum = sum + element;
}

Equivalent to

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


{
double element = data[i];
sum = sum + element;
}
– Notice:
• enhanced for loop does not allow you to modify the
content of an array
• iterate thru every element (you can not skip any one)

for (double element : data) //enhanced for loop


{
element = 0; //Error
}

for (int i = 0; i < data.length; i++) // regular for loop


{
data[i] = 0; //OK
}
Common Array Algorithm
• Filling

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


{
data[i] = i * i;
}
• Maximum and Minimum
double largest = data[0];
for (int i = 1; i < data.length ; i++)
{
if (data[i] > largest)
{
largest = data[i];
}
}
• Element Separators: e.g., 23 | 34| 87| 53
for (int i = 0; i < data.length; i++)
{
if (i > 0)
{
System.out.print(“ | “);
}
System.out.println(data[i]);
}
• For comma separator, such as [32, 45, 67, 83]
– Arrays.toString(data)

System.out.println(“data=“+Arrays.toString(data));
Linear Search/Sequential Search
int searchValue = 100;
int pos = 0;
boolean found = false;
while (pos < data.length && !found)
{
if (data[pos] == searchedValue)
{
found = ture;
}
else
{
pos++;
}
}
if (found){ System.out.println(“Found at position: “ + pos);}
else { System.out.println(“Not found”); }
• For a sorted array, you can use binary search
Removing an Element
• Suppose you want to remove the element with index
pos from the array data
• Case I: order is not important, just move element to
overwrite the element at index pos
data[pos] = data[currentSize – 1];
currentSize--;
• Case II: order matters
for (int i = pos; i < currentSize - 1; i++)
{
data[i] = data[i+1];
}
currentSize--;
Inserting an Element
• Case I: order does not matter
if (currentSize < data.length)
{
data[currentSize] = newElement;
currentSize++;
}
• Case II: order does matter
if (currentSize < data.length)
{
for (int i = currentSize; i > pos; i--)
{
data[i] = data[i – 1];
}
data[pos] = newElement;
currentSize++;
}
Copying Arrays
Double[] data = new double[6];
• Case I: get another reference to the same
array
double[] prices = data;
• Case II: Make a true copy
double[] prices = Arrays.copyOf(data, data.length);
• Case III: Grow an array
double[] newData = Arrays.copyOf(data, 2 * data.length);
data = newData;
• copyOf was added in Java 6
• In Java 5, uses the following code for copying
double[] newData = new double[n];
for (int i = 0; i < n && i < data.length; i++)
{
newData[i] = data[i];
}
Reading Input
• For known input values
double[] inputs = new
double[NUMBER_OF_INPUTS];
for (i = 0; i < inputs.length; i++)
{
inputs[i] = in.nextDouble();
}
• For unknown number of input
int currentSize = 0;
while (in.hasNextDouble() && currentSize <
inputs.length)
{
inputs[currentSize] = in.nextDouble();
currentSize++;
}
• It will drop inputs after the array is filled
• Grow array to hold all inputs
double[] inputs = new double[INITIAL_SIZE];
int currentSize = 0;
while (in.hasNextDouble())
{
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = in.nextDouble();
currentSize++;
}
// discard unfilled elements
inputs = Arrays.copyOf(inputs.currentSize);
Problem Solving
• Mark the largest value in an input sequence
– Steps:
• Read input and find the largest value
• Print the input value and identify the largest value
import java.util.Scanner;

public class LargestInArray


{
public static void main(String[] args)
{
final int LENGTH = 100;
double[] data = new double[LENGTH];
int currentSize = 0;

System.out.println(“Please enter values, Q to quit:”);


Scanner in = new Scanner(System.in);
while (in.hasNextDouble() && currentSize < data.length)
{
data[currentSize] = in.nextDouble();
currentSize++;
}

double largest = data[0];


for (int i = 1; i< currentSize; i++)
{
if (data[i] > largest)
{
largest = data[i];
}
}
for (int i = 0; i < currentSize; i++)
{
System.out.print(data[i]);
if (data[i] == largest)
{
System.out.print(“ <== largest value”);
}
System.out.println();
}
}

// session suns as
Please enter values, Q to quite:
35 80 115 44.5 Q
35
80
115 <== largest value
44.5
Why Not???
double largest = 0;
for (int i = 0; i < data/length; i++)
{
if (data[i] > largest)
{
largest = data[i];
}
}
System.out.print(data[0]);
for (int i = 1; i < data.length; i++)
{
System.out.print(“, “ + data[i]);
}
for (pos = 0; pos < data.length && !found;
pos++)
{
if data[pos] > 100;
{
found = true;
}
}
for (int i = pos; i < currentSize – 1; i++)
{
data[i + 1] = data[i];
}
A Sorting Algorithm
• Selection sort
– Not efficient, but simple
• Java library provides an efficient sort method

Arrays.sort(data)

// for partially filled array


Arrays.sort(data, 0, currentSize); // for partially filled
array
Selection Sort
• Find the smallest one and swap with the
current position
11 9 17 5 12 // current pos: 0 smallest pos: 3
Þ 5 9 17 11 12 //current pos:1 smallest pos: 1
Þ 5 9 17 11 12 // current pos: 2 smallest pos:3
Þ 5 9 11 17 12 // current pos: 3 smallest pos: 4
Þ 5 9 11 12 17 //current pos: 4 unprocessed length:1, done
for (int unsorted = 0; unsorted < data.length - 1; unsorted++)
{
// find the position of the minimum
int minPost = unsorted;
for (int i = unsorted + 1; i < data.length; i++)
{
if (data[i] < data[minPos]){ minPos = i; }
}
// Swap the minimum into the sorted area
if (minPos != unsorted)
{
doube temp = data[minPos];
data[minPos] = data[unsorted];
data[unsorted] = temp;
}
}
Binary Search
• Faster than linear search for a sorted array
– Cut the size of the search in half in each step
• Given: 1 5 8 9 12 17 20 32
Is 15 in the array?
• Find if the value is in the first or second half of the
array
• 15 >= 9 (the last element of the first half)
• So let’s focus on data[4] to data[7]
• 15 <= 17 (the last of the first half)
• So let’s focus on data[4] and data[5]
• And so on ……
boolean found = false;
int low = 0;
int high = data.length – 1;
int pos = 0;
while (low <= high && !found)
{
pos = (low + high) / 2; // midpoint of the subsequence
if (data[pos] == searchValue) { found = true; }
else // look in second half
if (data[pos] < searchValue) { low = pos + 1;}
else { high = pos -1; } // look in first half
}
if (found)
{ System.out.println(“Found at position “ + pos): }
else
{ System.out.println(“Not found. Insert before position “ + pos); }
Methods Processing Array
• Array occurs as method parameters and/or return values
• Example: sum up an array of floating[point numbers
public static double sum(double[] data)
{
double total = 0;
for (double element : data)
{
total = total + element;
}
return total;
}
• Multiple all values by a given factor
public static void multiple(double[] data, double
factor)
{
for (int i = 0; i < data.length; i++)
{
data[i] = data[i] * factor;
}
}
• Return an array of squares from 02 up to (n-1)2
public static int[] squares(int n)
{
int[] result = new int[n];
for (int i = 0; i < n; i++)
{
result[i] = I * I;
}
return result;
}
Put Them Together
• Reads, scales and reverses a sequence of numbers
Import java.util.Scanner;
public class Reverse
{
public static void main(String[] args)
{
double[] values = readInputs(5);
multiply(values, 10);
printReversed(values);
}
public static double[] readInputs(int numberOfInputs)
{
System.out.println(“Enter “ + numberOfInputs + “
numbers: “);
Scanner in = new Scanner(System.in);
double[] inputs = new double[numberOfInputs];
for (int i = 0; i < inputs.length; i++)
{
inputs[i] = in.nextDouble();
}
return inputs;
}
public static void multiply(double[] data, double
factor)
{
for (int i = 0; i < data.length; i++)
{
data[i] = data[i] * factor;
}
}
public static void printReversed(double[] data)
{
for (int i = data.length – 1; i >= 0; i--)
{
System.out.print(data[i] + “ “);
}
System.out.println();
}
}
Two Dimensional Array
• Two-dimensional layout
• Matrix
• To store tabular data
• Declare Two-Dimensional Arrays
– Number of rows x Number of columns
– E.g., double[][] tableEntries = new double[7][3];
– E.g., int[][] data = {
{ 16, 3, 2, 13},
{5, 10, 11, 8},
{9, 6, 7, 12}
};
• Can not change the size of a two-dimensional
array once it has been declared
• Accessing Elements
– E.g., array[i][j]
– You can use two nested loops to access all values
in a two-dimensional array
Example
• The following data shows the figure skating
competitions at one Winter Olympics
Gold Silver Bronze
Canada 0 0 1
China 0 1 1
Japan 1 0 0
Russia 3 0 1
Switzerland 0 1 0
Ukraine 0 0 1
United States 0 2 0
Prints a table of medal winner counts with row totals
Public class Medals
{
public static void main(String[] args)
{
final int COUNTRIES = 7;
final int MEDALS = 3;

String[] countries =
{
“Canada”,
“China”,
“Japan”,
“Russia”,
“Switzerland”,
“Ukraine”,
“United States”
};
int[][] counts =
{
{ 0, 0, 1},
{0, 1, 1},
{1, 0, 0},
{3, 0, 1},
{0, 1, 0},
{0, 0, 1},
{0, 2, 0}
};
System.out.println(“ Country Gold Silver
Bronze Total”);
for (int i = 0; i < COUNTRIES; i++)
{
System.out.printf(“%15s”, countries[i]);
int total = 0;
for (int j = 0; j < MEDALS; j++)
{
System.out.printf(“%8d”, counts[i][j]);
total = total + counts[i][j];
}
System.out.printf(“%8d\n”, total);
}
}
Array Lists
• Stores a sequence of values whose size can
change
– Grow and shrink as needed
– Supplies methods for common tasks
• get
• set
• add // append
• Remove
• size
• Declaring and Using Array Lists
ArrayList<Type>
• Collects elements of the specific type
• Generic class
• Contained in java.util
– Import java.util.ArrayList
• E.g.,
ArrayList<String> friends = new ArrayList<String>();
friends.add(“Cindy”);
String name = friends.get(0);
friends.set(2, “Harry”);
• Watch out
ArrayList<String> names;
names.add(“Harry”); // Error – why?

int I = names.size();
name = names.get(i); // Error – why?

• Print the whole array


System.out.println(names);
Enhanced for loop
ArrayList<String> names = …;
for (String name : names)
{
System.out.println(name);
}

for (int i = 0; i < names.size(); i++)


{
String name = names.get(i);
System.out.println(name);
}
Short Summary
ArrayList<String> names = new ArrayList<String>();
names.add(“Ann”);
names.add(“Cindy”);
System.out.println(names);
names.add(1, “Bob”);
names.remove(0);
names.set(0, “Bill”);
String name = names.get(1);
String last = names.get(names.size() – 1);
ArrayList<Integer> squares = new
ArrayList<Integer>();
For (int i = 0; i < 10; i++)
{
squares.add(i * i);
}
• Wrappers and auto-boxing
– To collect numbers in array list, wrapper class has
to be used for primitive types
Primitive Type Wrapper Class

byte Byte

boolean Boolean

char Character

double Double

float Float

int Integer

long Long

short Short
• Boxing Double wrapper = 29.95;
• Unboxing double x = wrapper;
• Automatic

ArrayList<Double> data = new ArrayList<Double>();


Data.add(29.5);
double x = data.get(0);
Copying Array Lists
Case I:
ArrayList<String> friends = names;
friends.add(“Harry”);

Case II:
ArrayList<String> newNames = new
ArrayList<String>(names);
• Hit:
– Reference the same array
– Make a copy of an array
– But which is which?
Using ArrayList in Methods
public static ArrayList<String> reverse(ArrayList<String>
names)
{
ArrayList<String> result = new ArrayList<String>();

for (int i = names.size()-1; i >= 0; i--)


{
result.add(names.get(i));
}
return result;
}
Some Algorithms
double largest = data[0];
for (int i = 1; i < data.length; i++)
{
if (data[i] > largest)
{
largest = data[i];
}
}

double largest = data.get(0);


for (int i = 1; i < data.size(); i++)
{
if (data.get(i) > largest)
{
largest = data.get(i);
}
}
• Collect unknown number of input

ArrayList<Double> inputs = new


ArrayList<Double>();
while (in.hasNextDouble())
{
inputs.add(in.nextDouble());
}
Choosing Between Array Lists and Arrays

• Size never changes => array


• All primitive types => array
• Otherwise => array list
Comparison
Operation Arrays Array Lists

Get an element x= data[4] x = data.get(4)

Replace an element data[4] = 35 data.set(4, 35)

Number of elements data.length data.size()

Number of filled element Use a variable such as data.size()


currentSize (See slices in
array section)
Remove an element See the slices in array data.remove(4)
section
Add an element, growing See the slices in array data.add(35)
the collection section
Initializing a collection int[] data = {1, 4, 9} No initializer; call add
function
Length and Size
Data Type Number of Elements

Array a.length

Array list a.size()

String a.length()
Largest in Array List
import java.util.ArrayList;
import java.util.Scanner;
public class LargestInArrayList
{
public static void main(String[] args)
{
ArrayList<Double> data = new ArrayList<Double>();

System.out.println(“Please enter values, Q to quit:”);


Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
data.add(in.nextDouble());
}
double largest = data.get(0);
for (int i = 1; i < data.size(); i++)
{
if (data.get(i) > largest)
{
largest = data.get(i);
}
}
for (double element : data)
{
System.out.print(element);
if (element == largest)
{
System.out.print(“ <= largest value”);
}
System.out.println();
}
}

You might also like