5. ArrayList and wrapper classes
5. ArrayList and wrapper classes
Wrapper Classes
COMP2396 Object-Oriented Programming and Java
Dr. Kenneth Wong
Arrays
In Java, arrays are objects and they live on the heap
Unlike many other objects, arrays in Java
Do not have any method (save for those inherited from the
Object class)
Have one and only one instance variable (i.e., length)
Use special array syntax (i.e., the subscript operator [])
that is not used anywhere else in Java
Limitations
The size of an array must be determined at the time of
creation, and cannot be changed afterwards
Data (primitives or references) can be put into and read
from an array using array syntax, but cannot be actually
removed from the array
1
Arrays
Example
Dog[] myDogs = new Dog[4];
Creating a Dog array with 4 elements
for (int i = 0; i < myDogs.length; i++) {
myDogs[i] = new Dog();
} Putting a Dog reference into the array
ArrayList
is the answer!
3
ArrayList
ArrayList is a class in the core Java library (the API)
Can be used in your code as if you wrote it yourself
ArrayList
add(Object elem)
Adds the object parameter to the list
remove(int index)
Removes the object at the index parameter
remove(Object elem)
Removes this object (if it is in the ArrayList)
contains(Object elem)
Returns true if there is a match for the object parameter
isEmpty()
Returns true if the list has no element
indexOf(Object elem)
Returns the index of the object parameter or -1
size()
Returns the number of elements currently in the list
get(int index)
Returns the object currently at the index parameter
…
4
ArrayList
The type parameter in the
angle-brackets specifies the
Example type of objects that can be
// create an ArrayList stored in the ArrayList
ArrayList<Egg> myList = new ArrayList<Egg>();
// find out how many things are in it The size() method returns
int theSize = myList.size(); the number of elements
currently in the list (i.e., 2)
// find out if it contains something
boolean isIn = myList.contains(a);
The contains() method returns true as
the ArrayList does contain (a reference
to) the object referenced by a 5
ArrayList
Example
// find out where something is (i.e., its index)
int idx = myList.indexOf(b);
The indexOf() method returns
// find out if it is empty the (zero-based) index of the
object referenced by b (i.e., 1)
boolean empty = myList.isEmpty();
6
ArrayList vs Regular Array
ArrayList regular array
ArrayList<String> myList = new ArrayList<String>(); String[] myList = new String[2];
14
Packages
A class has a full name which is a combination of the
package name and the class name
e.g.,
java.util.ArrayList
public MyClass {
ArrayList<Dog> list;
// ...
}
16
How to Play with the API
Use the HTML API docs
Java comes with a fabulous set of online docs
http://docs.oracle.com/javase/8/docs/api/index.html
17
Wrapper Classes
The type parameter of an ArrayList supports classes only
(i.e., it is not possible to create ArrayLists of primitive types)
There is a wrapper class for Primitive Type Wrapper
every primitive type such that a Class
primitive can be treated like an
boolean Boolean
object
char Character
Each wrapper class is named byte Byte
after the primitive type (save for
char and int), but with the first short Short
letter capitalized int Integer
long Long
The wrapper classes are in the
java.lang package (i.e., no float Float
import statement is needed) double Double
20
Autoboxing
The autoboxing feature in Java blurs the line between
primitives and wrapper objects
Autoboxing performs the conversion from primitives to
wrapper objects, and vice versa, automatically
Example
import java.util.*;
21
Autoboxing
Autoboxing works almost everywhere
Assignments
One can assign either a wrapper or primitive to a
variable declared as a matching wrapper or primitive
type, e.g.,
int p = new Integer(42);
Integer q = p;
22
Autoboxing
Method arguments
If a method takes a primitive, one can pass in either a
compatible primitive or a reference to a wrapper of
that primitive type
public void takePrimitive(int i) { … }
23
Autoboxing
Return values
If a method declares a primitive return type, one can
return either a compatible primitive or a reference to
the wrapper of that primitive type
public int returnPrimitive() { … }
24
Autoboxing
Boolean expressions
Any place a boolean value is expected, one can use
either an expression that evaluates to a boolean, a
primitive boolean, or a reference to a Boolean
wrapper
if (bool) { … }
25
Autoboxing
Operations on numbers
One can use a wrapper type as an operand in
operations where the primitive type is expected
e.g.,
Integer i = new Integer(42);
i++;
26
Autoboxing
Example
public class TestBox {
Integer i;
int j;
27
Autoboxing
Example
public class TestBox {
Integer i;
int j;
28
Autoboxing
Example
This instance variable will
public class TestBox { get a default value of null
Integer i;
int j;
29
String to Primitive
The wrapper classes have static parse methods that
take a string and return a primitive value
Examples
String s = "2";
int x = Integer.parseInt(s);
double d = Double.parseDouble("420.24");
boolean b = Boolean.parseBoolean("True");
String t = "two";
int y = Integer.parseInt(t);
This compiles just fine, but at
runtime it blows up. Anything that
cannot be parsed as a number will
cause a NumberFormatException
30
Primitive to String
The easiest way to turn a number into a string is by
simply concatenating the number to an existing
string, e.g.,
double d = 42.5;
String doubleString = "" + d;
31
Number Formatting
In Java, formatting numbers is a simple matter of
calling the static format() method of the String class
format string
The rest of the arguments to the format() method are
the numbers to be formatted by the format specifiers
32
Number Formatting
Some common format specifiers
"%,d" means “inserts commas and format the number as a
decimal integer”
"%.2f" means “format the number as a floating point with a
precision of 2 decimal places”
"%,.2f" means “inserts commas and format the number as
a floating point with a precision of 2 decimal places”
"%,5.2f" means “insert commas and format the number as
a floating point with a precision of 2 decimal places and
with a minimum of 5 characters, padding spaces and
zeros as appropriate”
"%h" means “format the number as a hexadecimal”
"%c" means “format the number as a character”
33
Number Formatting
Example
System.out.println(String.format("Balance = %,d", 10000));
System.out.println(String.format("10000 / 3 = %.2f", 10000.0/3));
System.out.println(String.format("10000 / 3 = %,.2f", 10000.0/3));
System.out.println(String.format("10000 / 3 = %,10.2f", 10000.0/3));
System.out.println(String.format("255 = %h in hexadecimal", 255));
System.out.println(String.format("ASCII code 65 = %c", 65));
Sample output
Balance = 10,000
10000 / 3 = 3333.33
10000 / 3 = 3,333.33
10000 / 3 = 3,333.33
255 = ff in hexadecimal
ASCII code 65 = A
34