Big Java - Colorado School of Mines
Download
Report
Transcript Big Java - Colorado School of Mines
Collections of Data
ARRAYLIST
ArrayLists
• Array lists can grow and shrink as needed
• ArrayList is a generic class (similar to C++ template)
• ArrayList has variety of methods for common tasks, for
example:
ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
// insert using add method
accounts.add(new BankAccount(1001));
accounts.add(new BankAccount(2010));
// retrieve using get method
BankAccount anAccount = accounts.get(1);
// find out how many items in list
int count = accounts.size(); // 0 to size-1 are valid
BankAccount account2 = new BankAccount(3000);
// update the list
accounts.set(1, account2); // overwrites
accounts.add(0, new BankAccount(1200)); // index < size
// remove an item
accounts.remove(1);
// access all items in order
for (int i=0; i<accounts.size(); ++i)
System.out.println(accounts.get(i).getBalance());
ArrayList (continued)
• With an unparameterized ArrayList, any
type of object may be stored, but the
object must be cast when retrieved:
ArrayList accounts = new ArrayList();
accounts.add(new BankAccount(1500));
BankAccount acct = (BankAccount) accounts.get(0);
•
Exception will occur if cast is incorrect. Much
better practice to use generic class (warning in
Eclipse if use unparameterized)
Wrappers and Auto-boxing
• Not in C++ (C++ evolved
from C, Java designed
from scratch as OO)
• Numbers are not objects,
can’t place directly in
ArrayLists
• All primitive types have
“wrapper” classes
• Wrapper contains one
value of corresponding
primitive type
• Also have useful static
methods (mostly
conversions)
Primitive
Wrapper
byte
Byte
boolean
Boolean
char
Character
double
Double
float
Float
int
Integer
long
Long
short
Short
Wrappers and Auto-boxing (continued)
• Starting with Java 5.0, conversion between
primitive types and wrapper classes is automatic,
called auto-boxing (auto-wrapping would be more
consistent!)
• Examples:
Double d = 29.95;
// Double d = new Double(29.95);
double x = d;
// auto-unbox, same as double x = d.doubleValue();
Double e = d + 1;
// auto-unbox, add 1, auto-box
ArrayList<Double> data = new ArrayList<Double>();
data.add(32.14);
double x = data.get(0);
Efficiency Note
• Even though you don’t have to write the
code, if you have a long sequence of
primitive types (numbers or chars), use
an array rather than an ArrayList for
efficiency
Enhanced/Iterated for loop
• Convenient new syntax for iterating an array or
ArrayList:
double[] data = { . . . };
double sum = 0;
for (double e : data)
{
sum = sum + e;
}
• With ArrayLists:
ArrayList<BankAccount> accounts;
. . . add, create sum
for (BankAccount a : accounts)
{
sum += a.getBalance();
}
2D Arrays
• Similar to C++, but must always allocate
memory
final int ROWS = 3;
final int COLS = 3;
String[][] board = new String[ROWS][COLS];
More on Arrays etc.
• First choice will normally be ArrayList, unless
storing large collection of primitives OR need 2D
• Use “for each” loop pattern when processing all
elements
• To make a copy, use the clone method*:
double [] data = new double[10];
. . .
double [] prices = (double []) data.clone();
• Or use System.arraycopy if not copying the entire
array (see book or API for details)
•
Clone has some flaws (must call super.clone, issues depending on whether new is called,
issues with CloneNotSupportedException). Probably OK to use for arrays, but copy
constructor often preferred for other object. Details are beyond our scope… but read the
following:
http://stackoverflow.com/questions/2427883/clone-vs-copy-constructor-which-isrecommended-in-java
Vector or ArrayList?
• The API for these is similar, but there are
some differences in implementation.
• If you’re curious, check out:
• http://www.javaworld.com/article/207742
5/java-se/vector-or-arraylist-which-isbetter.html?null