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

5. ArrayList and wrapper classes

The document discusses the differences between arrays and ArrayLists in Java, highlighting that arrays have a fixed size and limited functionality while ArrayLists can dynamically grow and shrink. It explains the methods available in ArrayLists, such as add, remove, and contains, and contrasts these with the limitations of regular arrays. Additionally, it covers the concept of wrapper classes for primitive types, which allow primitives to be treated as objects in ArrayLists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

5. ArrayList and wrapper classes

The document discusses the differences between arrays and ArrayLists in Java, highlighting that arrays have a fixed size and limited functionality while ArrayLists can dynamically grow and shrink. It explains the methods available in ArrayLists, such as add, remove, and contains, and contrasts these with the limitations of regular arrays. Additionally, it covers the concept of wrapper classes for primitive types, which allow primitives to be treated as objects in ArrayLists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

ArrayList and

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

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


Dog dog = myDogs[i];
Getting a Dog reference from the array
dog.makeNoise();
}

myDogs[2] = null; “Removing” a Dog reference from the array

for (Dog dog : myDogs) {


if (dog != null) {
The size of the array does not change
dog.makeNoise();
}
} 2
Arrays
 Wouldn’t it be fantastic if an array
 Could grow when you add something to it?
 Could shrink when you remove something from it?
 Could tell you if it contains what you’re looking for
without having you to loop through and check each
element?
 Could let you get things out of it without having you
to know exactly which slots the things are in?

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>();

// put something into it


Egg a = new Egg();
The ArrayList grows when an item is added to it
myList.add(a);

// put another thing into it


Egg b = new Egg(); The ArrayList grows when an item is added to it
myList.add(b);

// 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();

// Remove something from it The isEmpty() method returns false


myList.remove(a); as the ArrayList is not empty

// loop through it The ArrayList shrinks when


for (Egg egg : myList) { an item is removed from it
// egg.xxxx
}
The enhanced for loop can be applied
to loop through the ArrayList

6
ArrayList vs Regular Array
ArrayList regular array
ArrayList<String> myList = new ArrayList<String>(); String[] myList = new String[2];

String a = new String("whoohoo"); String a = new String("whoohoo");


myList.add(a); myList[0] = a;

String b = new String("Frog"); String b = new String("Frog");


myList.add(b); myList[1] = b;

int theSize = myList.size(); int theSize = myList.length;

String s = myList.get(1); String s = myList[1];

myList.remove(1); myList[1] = null;

boolean isIn = myList.contains(b); boolean isIn = false;


for (String item : myList) {
if (b.equals(item)) {
isIn = true;
break;
}
}
7
ArrayList vs Regular Array
ArrayList regular array
ArrayList<String> myList = new ArrayList<String>(); String[] myList = new String[2];

String a = new String("whoohoo"); String a = new String("whoohoo");


myList.add(a); myList[0] = a;

String b = new String("Frog"); String b = new String("Frog");


An ArrayList does not need to know its
myList.add(b); myList[1] = b;
size at the time of creation. It grows A regular array has to know its
and
int shrinks
theSize as objects are added or
= myList.size(); size at the time of creation
int theSize = myList.length;
removed from it
String s = myList.get(1); String s = myList[1];

myList.remove(1); myList[1] = null;

boolean isIn = myList.contains(b); boolean isIn = false;


for (String item : myList) {
if (b.equals(item)) {
isIn = true;
break;
}
}
8
ArrayList vs Regular Array
ArrayList regular array
ArrayList<String> myList = new ArrayList<String>(); String[] myList = new String[2];

String a = new String("whoohoo"); String a = new String("whoohoo");


myList.add(a); myList[0] = a;

String b = new String("Frog"); String b = new String("Frog");


myList.add(b); myList[1] = b;

int theSize = myList.size(); int theSize = myList.length;

String s = myList.get(1); An object must be assigned to a


String s = myList[1];
An object can be added without
specific location (zero-based
specifying a location (i.e., an
myList.remove(1); index) in a regular array. If the
myList[1] = null;
index) in an ArrayList. The
index is outside the boundaries of
ArrayList
boolean isIn will keep growing to
= myList.contains(b); boolean isIn = false;
the array, it blows up at runtime
make room for the new thing for (String item : myList) {
if (b.equals(item)) {
isIn = true;
break;
}
}
9
ArrayList vs Regular Array
ArrayList regular array
ArrayList<String> myList = new ArrayList<String>(); String[] myList = new String[2];
The (dynamic) size of an
String a = new String("whoohoo");
The size of a regular array
String a = new String("whoohoo");
ArrayList can be retrieved by
myList.add(a); myList[0] = a; is stored in its (final)
calling its size() method instance variable length
String b = new String("Frog"); String b = new String("Frog");
myList.add(b); myList[1] = b;

int theSize = myList.size(); int theSize = myList.length;

String s = myList.get(1); String s = myList[1];

myList.remove(1); myList[1] = null;

boolean isIn = myList.contains(b); boolean isIn = false;


for (String item : myList) {
if (b.equals(item)) {
isIn = true;
break;
}
}
10
ArrayList vs Regular Array
ArrayList regular array
ArrayList<String> myList = new ArrayList<String>(); String[] myList = new String[2];

String a = new String("whoohoo"); String a = new String("whoohoo");


myList.add(a); myList[0] = a;
A regular array uses array
An ArrayList is just a plain Java
String b = new String("Frog"); syntax
String b = new that is not used
String("Frog");
object, and uses no special syntax
myList.add(b); anywhere else in Java
myList[1] = b;

int theSize = myList.size(); int theSize = myList.length;

String s = myList.get(1); String s = myList[1];

myList.remove(1); myList[1] = null;

boolean isIn = myList.contains(b); boolean isIn = false;


for (String item : myList) {
if (b.equals(item)) {
isIn = true;
break;
}
}
11
ArrayList vs Regular Array
ArrayList regular array
ArrayList<String> myList = new ArrayList<String>(); String[] myList = new String[2];

String a = new String("whoohoo"); String a = new String("whoohoo");


myList.add(a); myList[0] = a;

String b = new String("Frog"); String b = newAn object cannot be actually


String("Frog");
An object can be removed
myList.add(b); removed from a regular array
myList[1] = b;
from an ArrayList and the (assigning null to an array element
int theSize = myList.size(); int theSize = myList.length;
ArrayList shrinks accordingly does not change the array size)
String s = myList.get(1); String s = myList[1];

myList.remove(1); myList[1] = null;

boolean isIn = myList.contains(b); boolean isIn = false;


for (String item : myList) {
if (b.equals(item)) {
isIn = true;
break;
}
}
12
ArrayList vs Regular Array
ArrayList regular array
ArrayList<String> myList = new ArrayList<String>(); String[] myList = new String[2];

String a = new String("whoohoo"); String a = new String("whoohoo");


myList.add(a); myList[0] = a;

String b = new String("Frog"); String b = new String("Frog");


myList.add(b); myList[1] = b;

An ArrayList can tell if it


int theSize = myList.size(); int theSize = There
myList.length;
is no simply way to check
contains an object by calling if an object is in a regular array
String s = myList.get(1);
its contains() method String s = myList[1];
without having to loop through
myList.remove(1); myList[1] = null; and check each element

boolean isIn = myList.contains(b); boolean isIn = false;


for (String item : myList) {
if (b.equals(item)) {
isIn = true;
break;
}
}
13
Packages
 In the Java API, classes are grouped into packages
(e.g., ArrayList is in the package java.util which
holds a pile of utility classes)
 Packages are important for 3 main reasons
 Help the overall organization (classes are grouped
into packages for specific kinds of functionality, e.g.,
GUI, data structures, etc.)
 Provide a name-scoping that helps to prevent
collisions of names
 Provide a level of security (allowing placing
restrictions on code such that only other classes in
the same package can access it)

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

package name class name


 To use a class in a package other than java.lang, the full
name of the class must be specified
e.g.,
java.util.ArrayList<Dog> list = new java.util.ArrayList<Dog>();

public void go(java.util.ArrayList<Dog> list) { … }


parameter type
public java.util.ArrayList<Dog> foo() { … }
return type
15
Packages
 Alternatively, include an import statement at the top of the
source code to avoid typing the full name everywhere, e.g.,
import java.util.ArrayList;

public MyClass {
ArrayList<Dog> list;
// ...
}

 It is also possible to import all classes in a package using a


wildcard character *, e.g.,
import java.util.*;

 Note that an import statement simply saves you from typing


the full name of a class, it will not make your code bloated or
slower

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

 The API docs are the best


reference for
 Finding out what are in the
Java library
 Getting details about a class
and its methods

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

Watch out! The names


are not mapped exactly
to the primitive types
18
Wrapper Classes
 Examples: wrapping a value
boolean b = true;
Boolean bWrap = new Boolean(b);
char c = 'K';
Character cWrap = new Character(c);
int i = 288;
Integer iWrap = new Integer(i); Simply give the primitive to the
double d = 1.234567; constructor of the wrapper class
Double dWrap = new Double(d);

 Examples: unwrapping a value


boolean bUnWrap = bWrap.booleanValue();
char cUnWrap = cWrap.charValue();
int iUnWrap = iWrap.intValue();
All the wrapper classes work
double dUnWrap = dWrap.doubleValue();
like this. E.g., Byte has a
byteValue() method, Short has
a shortValue() method, etc.
19
An ArrayList of a Primitive Type
 Example
import java.util.*;

public class WithoutAutoBoxing {


public static void main(String[] args) {
ArrayList<Integer> listOfNumbers = new ArrayList<Integer>();
listOfNumbers.add(new Integer(3));
Wrap an int value 3 into
Integer num = listOfNumbers.get(0);
an Integer object and
int intNum = num.intValue();
add it to the ArrayList
}
}
Unwrap an int value
from an Integer object

 The wrapping and unwrapping of primitives sound


rather tedious

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.*;

public class WithAutoBoxing {


public static void main(String[] args) {
ArrayList<Integer> listOfNumbers = new ArrayList<Integer>();
listOfNumbers.add(3);
The compiler does all the
int intNum = listOfNumbers.get(0);
wrapping (boxing) for you
}
}
The compiler unwraps (unboxes)
the Integer object automatically

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) { … }

 If a method takes a wrapper type, one can pass in


either a reference to a wrapper or a primitive of the
matching type
public void takeWrapper(Integer 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() { … }

 If a method declares a wrapper return type, one can


return either a reference to a wrapper or a primitive
of the matching type
public Integer returnWrapper() { … }

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++;

Integer j = new Integer(5);


Integer k = j + 3;

26
Autoboxing
 Example
public class TestBox {
Integer i;
int j;

public static void main(String[] args) {


TestBox t = new TestBox();
t.go();
} Will this code compile?
Will it run?
public void go() { If it runs, what will it do?
j = i;
System.out.println(j);
System.out.println(i);
}
}

27
Autoboxing
 Example
public class TestBox {
Integer i;
int j;

public static void main(String[] args) {


TestBox t = new TestBox();
t.go();
} Will this code compile? Yes
Will it run? Yes, but with error
public void go() { If it runs, what will it do?
j = i;
System.out.println(j);
System.out.println(i);
}
}

28
Autoboxing
 Example
This instance variable will
public class TestBox { get a default value of null
Integer i;
int j;

public static void main(String[] args) {


TestBox t = new TestBox();
t.go();
}
Autoboxing fails as i is not
public void go() { referencing any valid Integer
j = i; object. This will result in a
System.out.println(j); NullPointerException
System.out.println(i);
}
}

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;

 Alternatively, this can be done by calling the static


toString() method of a wrapper class, e.g.,
double d = 42.5;
String doubleString = Double.toString(d);

31
Number Formatting
 In Java, formatting numbers is a simple matter of
calling the static format() method of the String class

 The first argument to the format() method is called the


format string, and it can include characters that are
printed as-is, together with one or more format
specifiers that begin with a percentage sign (%)
e.g., format specifier

String s = String.format("This cat weights %.2fkg", 4.3333);

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

You might also like