Arrays and Array List
Arrays and Array List
double[] data = …
double sum = 0;
Equivalent to
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;
// 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)
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?
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
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>();
Array a.length
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>();