|
Computer Science (CSCI)
Department |
|||
|
|||
ArrayList & Arrays
(Example code and figures from Computing Concepts with Java
Essentials, 3rd edition, by Cay Horstmann.
Visit www.wiley.com/college/horstmann
for information on the current edition of this excellent text.)
ArrayList
ArrayList coins = new ArrayList(); |
Retrieving ArrayList Elements
Coin c = (Coin)coins.get(0); // gets the first coin |
int n = coins.size(); |
for (int i = 0; i < coins.size(); i++) |
Adding and Removing Elements
coins.set(4, aNickel); |
add(i, c); |
public class Purse |
Counting
public class Purse |
Finding Maximum
public class Purse |
Storing Numbers in an Array List
// wrap the primitive type Double wrapper = new Double(29.95); // unwrap the primitive type double unwrapped = wrapper.doubleValue() // putting wrapped primitive in an ArrayList ArrayList data = new ArrayList(); data.add(wrapper); // getting it back out again unwrapped = ((Double).data.get(i)).doubleValue(); |
Arrays
new double[10] |
double[] data = new double[10]; |
data[4] = 29.95; |
Copying Arrays
double[] data = new double[10]; |
double[] prices = (double[])data.clone(); |
System.arraycopy(from, fromStart, to, toStart, count); |
Adding and Removing Array Elements
System.arraycopy(data, i, data, i + 1, data.length - i - 1); |
System.arraycopy(data, i + 1, data, i, data.length - i - 1); |
Partially Filled Arrays
final int DATA_LENGTH = 100; |
data[dataSize] = x; |
for (int i = 0; i < dataSize; i++) |
if (dataSize >= data.length) |
if (dataSize >= data.length)
{
|

|
Exercise - implement a Bank class
|