CS计算机代考程序代写 data structure Java compiler Chapter 5.

Chapter 5.
ArrayList and Wrapper Classes
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
1

Arrays
— InJava,arraysareobjectsandtheyliveontheheap — Unlikemanyotherobjects,arraysinJava
— Donothaveanymethod(saveforthoseinheritedfromthe Object class)
— Haveoneandonlyoneinstancevariable(i.e.,length)
— Usespecialarraysyntax(i.e.,thesubscriptoperator[]) that
is not used anywhere else in Java — Limitations
— Thesizeofanarraymustbedeterminedatthetimeof creation, and cannot be changed afterwards
— Data(primitivesorreferences)canbeputintoandread from an array using array syntax, but cannot be actually removed from the array
2

— Example
Dog[] myDogs = new Dog[4];
for (int i = 0; i < myDogs.length; i++) { myDogs[i] = new Dog(); } for (int i = 0; i < myDogs.length; i++) { Dog dog = myDogs[i]; dog.makeNoise(); } myDogs[2] = null; for (Dog dog : myDogs) { if (dog != null) { dog.makeNoise(); } Creating a Dog array with 4 elements Putting a Dog reference into the array Getting a Dog reference from the array “Removing” a Dog reference from the array The size of the array does not change Arrays } 3 Arrays — Wouldn’t it be fantastic if an array — Couldgrowwhenyouaddsomethingtoit? — Couldshrinkwhenyouremovesomethingfromit? — Couldtellyouifitcontainswhatyou’relookingfor without having you to loop through and check each element? — Couldletyougetthingsoutofitwithouthavingyouto know exactly which slots the things are in? ArrayList is the answer! 4 ArrayList — ArrayListisaclassinthecoreJavalibrary(theAPI) — Canbeusedinyourcodeasifyouwroteityourself 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 ... 5 ArrayList ArrayList myList = new ArrayList();
The type parameter in the angle-brackets specifies the type of objects that can be
stored in the ArrayList
— Example
// create an ArrayList
// put something into it
Egg a = new Egg(); myList.add(a);
// put another thing into it
Egg b = new Egg(); myList.add(b);
The ArrayList grows when an item is added to it The ArrayList grows when an item is added to it
// find out how many things are in it
int theSize = myList.size();
// find out if it contains something
boolean isIn = myList.contains(a);
The size() methodreturns the number of elements currently in the list (i.e., 2)
The contains() method returns true as the ArrayList does contain (a reference
to) the object referenced by a
6

ArrayList
— Example
// find out where something is (i.e., its index)
int idx = myList.indexOf(b); // find out if it is empty
boolean empty = myList.isEmpty(); // Remove something from it
myList.remove(a);
// loop through it
for (Egg egg : myList) { // egg.xxxx
}
The indexOf() method returns the (zero-based) index of the object referenced by b (i.e., 1)
The isEmpty() method returns false as the ArrayList is not empty
The ArrayList shrinks when an item is removed from it
The enhanced for loop can be applied to loop through the ArrayList
7

ArrayList vs Regular Array
ArrayList Regular Array
ArrayList myList = new ArrayList();
String[] myList = new String[2]; String a = new String(“whoohoo”);
String a = new String(“whoohoo”);
An ArrayList does not need to know its
myList.add(a);
size at the time of creation. It grows and shrinks as objects are added or removed
String b = new String(“Frog”);
from it. String s = myList.get(1);
myList.add(b);
myList[0] = a;
A regular array has to know its size at the time of creation
String b = new String(“Frog”); myList[1] = b;
int theSize = myList.length; String s = myList[1]; myList[1] = null;
boolean isIn = false;
for (String item : myList) {
if (b.equals(item)) { isIn = true;
break;
} }
8
int theSize = myList.size();
String s = myList.get(1); myList.remove(1);
boolean isIn = myList.contains(b);

ArrayList vs Regular Array
ArrayList Regular Array
ArrayList myList = new ArrayList();
String a = new String(“whoohoo”);
myList.add(a);
String b = new String(“Frog”);
myList.add(b);
String[] myList = new String[2]; String a = new String(“whoohoo”);
myList[0] = a;
String b = new String(“Frog”);
myList[1] = b;
int theSize = myList.length;
An object must be assigned to a specific location (zero-based index) in a regular
String s = myList[1];
array. If the index is outside the
myList[1] = null;
boundaries of the array, it blows up at runtime.
boolean isIn = false;
for (String item : myList) {
if (b.equals(item)) { isIn = true;
break;
} }
9
int theSize = myList.size();
An object can be added without specifying a location (i.e. an index) in an
String s = myList.get(1);
ArrayList. The ArrayList will keep
gmroyLwisitn.rgemtovem(1a);ke room for the new
boolean isIn = myList.contains(b);
thing.

ArrayList vs Regular Array
ArrayList Regular Array
ArrayList myList = new ArrayList();
String a = new String(“whoohoo”); myList.add(a);
String b = new String(“Frog”); myList.add(b);
int theSize = myList.size(); String s = myList.get(1);
String[] myList = new String[2];
String a = new String(“whoohoo”); myList[0] = a;
String b = new String(“Frog”); myList[1] = b;
int theSize = myList.length;
String s = myList[1];
myList[1] = null;
The size of a regular array is stored in its
(final) instance variable length boolean isIn = false;
The (dynamic) size of an ArrayList can be myList.remove(1);
retrieved by calling its size() method
boolean isIn = myList.contains(b);
for (String item : myList) { if (b.equals(item)) {
isIn = true;
break; }
}
10

ArrayList vs Regular Array
ArrayList Regular Array
ArrayList myList = new ArrayList();
String a = new String(“whoohoo”); myList.add(a);
String[] myList = new String[2];
String a = new String(“whoohoo”); myList[0] = a;
String b = new String(“Frog”); AmryeLgisut[l1a]r=abr;ray uses array syntax that is
not used anywhere else in Java
int theSize = myList.length;
String s = myList[1];
myList[1] = null;
boolean isIn = false;
for (String item : myList) {
if (b.equals(item)) { isIn = true;
break;
} }
11
An ArrayList is just a plain Java object,
String b = new String(“Frog”);
myList.add(b);
and uses no special syntax
int theSize = myList.size();
String s = myList.get(1); myList.remove(1);
boolean isIn = myList.contains(b);

ArrayList vs Regular Array
ArrayList Regular Array
ArrayList myList = new ArrayList();
String a = new String(“whoohoo”); myList.add(a);
String[] myList = new String[2];
String a = new String(“whoohoo”); myList[0] = a;
An object cannot be actually removed String b = new String(“Frog”);
from a regular array (assigning null to an
myList[1] = b;
array element does not change the array
size)
int theSize = myList.length;
String b = new String(“Frog”);
An object can be removed from an myList.add(b);
ArrayList and the ArrayList shrinks
accordingly
int theSize = myList.size();
String s = myList[1];
myList[1] = null;
boolean isIn = false;
for (String item : myList) {
if (b.equals(item)) { isIn = true;
break;
} }
12
String s = myList.get(1);
myList.remove(1);
boolean isIn = myList.contains(b);

ArrayList vs Regular Array
ArrayList Regular Array
ArrayList myList = new ArrayList();
String a = new String(“whoohoo”); myList.add(a);
String b = new String(“Frog”); myList.add(b);
String[] myList = new String[2];
String a = new String(“whoohoo”); myList[0] = a;
String b = new String(“Frog”); myList[1] = b;
int theSize = myList.length;
There is no simple way to check if an object is in a regular array without having
String s = myList[1];
to loop through and check each element
int theSize = myList.size();
An ArrayList can tell if it contains an
object by calling its contains() method
String s = myList.get(1);
myList.remove(1);
boolean isIn = myList.contains(b);
myList[1] = null;
boolean isIn = false;
for (String item : myList) {
if (b.equals(item)) { isIn = true;
break;
} }
13

Packages
— IntheJavaAPI,classesaregroupedintopackages (e.g.,ArrayList is in the package java.util which holds a pile of utility classes)

Packages are important for 3 main reasons
— Helptheoverallorganization(classesaregroupedinto packages for specific kinds of functionality, e.g., GUI, data structures, etc.)
— Provideaname-scopingthathelpstoprevent collisions of names
— Providealevelofsecurity(allowingplacingrestrictions on code such that only other classes in the same package can access it)
14

Packages
— Aclasshasafullnamewhichisacombinationofthe package name and the class name
e.g.,
java.util.ArrayList
package name class name
— Touseaclassinapackageotherthanjava.lang,thefull name of the class must be specified
e.g.,
java.util.ArrayList list = new java.util.ArrayList();
public void go(java.util.ArrayList list) { … }
parameter type return type
public java.util.ArrayList foo() { … }
15

Packages
— Alternatively,includeanimportstatementatthetopofthe source code to avoid typing the full name everywhere, e.g.,
import java.util.ArrayList;
public MyClass { ArrayList list; // …
}
— Itisalsopossibletoimportallclassesinapackageusinga wildcard character *, e.g.,
— Notethatanimportstatementsimplysavesyoufromtyping the full name of a class, it will not make your code bloated or slower
import java.util.*;
16

How to Play with the API
— UsetheHTMLAPIdocs
— Javacomeswithafabuloussetofonlinedocs
http://docs.oracle.com/javase/8/docs/api/index.html
— TheAPIdocsarethebest reference for
— Finding out what are in the Java library
— Gettingdetailsaboutaclass and its methods
17

Wrapper Classes
— ThetypeparameterofanArrayListsupportsclassesonly(i.e., it is not possible to create ArrayLists of primitive types)
— Thereisawrapperclassfor every primitive type such that a primitive can be treated like an object
— Eachwrapperclassisnamed after the primitive type (except char and int), but with the first letter capitalized
— Thewrapperclassesareinthe java.lang package (i.e., no import statement is needed)
Primitive Type
Wrapper Class
boolean
Boolean
char
Character
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
Watch out! The names are not mapped exactly to the primitive types
18

Wrapper Classes
— Examples:wrappingavalue
boolean b = true;
Boolean bWrap = new Boolean(b); char c = ‘K’;
Character cWrap = new Character(c); int i = 288;
Integer iWrap = new Integer(i); double d = 1.234567;
Double dWrap = new Double(d);
— Examples:unwrappingavalue boolean bUnWrap = bWrap.booleanValue();
char cUnWrap = cWrap.charValue(); int iUnWrap = iWrap.intValue();
double dUnWrap = dWrap.doubleValue();
Simply give the primitive to the constructor of the wrapper class
All the wrapper classes work 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 listOfNumbers = new ArrayList();
listOfNumbers.add(new Integer(3)); Integer num = listOfNumbers.get(0); int intNum = num.intValue();
}
Wrap an int value 3 into an Integer object and add it to the ArrayList
Unwrap an int value from an Integer object
— The wrapping and unwrapping of primitives sound rather tedious
20

Autoboxing
— TheautoboxingfeatureinJavablursthelinebetween primitives and wrapper objects
— Autoboxingperformstheconversionfromprimitivesto wrapper objects, and vice versa, automatically
— Example
import java.util.*;
public class WithAutoBoxing {
public static void main(String[] args) {
ArrayList listOfNumbers = new ArrayList();
listOfNumbers.add(3);
int intNum = listOfNumbers.get(0); }
The compiler does all the wrapping (boxing) for you
}
The compiler unwraps (unboxes) the Integer object automatically
21

Autoboxing
— Autoboxing works almost everywhere — Assignments
— Onecanassigneitherawrapperorprimitivetoa variable declared as a matching wrapper or primitive type, e.g.,
int p = new Integer(42); Integer q = p;
22

Autoboxing
— Methodarguments
— Ifamethodtakesaprimitive,onecanpassineithera compatible primitive or a reference to a wrapper of that primitive type
— Ifamethodtakesawrappertype,onecanpassin either a reference to a wrapper or a primitive of the matching type
public void takePrimitive(int i) { … }
public void takeWrapper(Integer i) { … }
23

Autoboxing
— Ifamethoddeclaresaprimitivereturntype,onecan returneitheracompatibleprimitiveorareference to the wrapper of that primitive type
— Ifamethoddeclaresawrapperreturntype,onecan return either a reference to a wrapper or a primitive of the matching type
— Return values
public int returnPrimitive() { … }
public Integer returnWrapper() { … }
24

Autoboxing
— Boolean expressions
— Anyplaceabooleanvalueisexpected,onecanuse either an expression that evaluates to a boolean, a primitive boolean, or a reference to a Boolean wrapper
if (bool) { … }
25

Autoboxing
— Operationsonnumbers
— Onecanuseawrappertypeasanoperandin 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

— Example
public class TestBox { Integer i;
int j;
public static void main(String[] args) { TestBox t = new TestBox(); t.go();
}
public void go() { j = i;
System.out.println(j);
System.out.println(i); }
}
Will this code compile? Will it run?
If it runs, what will it do?
Autoboxing
27

— Example
public class TestBox { Integer i;
int j;
public static void main(String[] args) { TestBox t = new TestBox(); t.go();
}
public void go() { j = i;
System.out.println(j);
System.out.println(i); }
}
Will this code compile? Yes Will it run? Yes, but with error If it runs, what will it do?
Autoboxing
28

— Example
public class TestBox { Integer i;
int j;
public static void main(String[] args) { TestBox t = new TestBox(); t.go();
}
public void go() { j = i;
System.out.println(j);
System.out.println(i); }
}
This instance variable will get a default value of null
Autoboxing
Autoboxing fails as i is not referencing any valid Integer object. This will result in a NullPointerException
29

String to Primitive
— Thewrapperclasseshavestaticparsemethodsthat 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”;
i n t 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
— Theeasiestwaytoturnanumberintoastringisby simply concatenating the number to an existing string, e.g.,
— Alternatively, this can be done by calling the static toString() method of a wrapper class, e.g.,
double d = 42.5; StringdoubleString=”” +d;
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 format string
String s = String.format(“This cat weights %.2fkg”, 4.3333);
— Therestoftheargumentstotheformat()methodarethenumbers to be formatted by the format specifiers
32

Number Formatting
— Somecommonformatspecifiers
— “%,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 / 33==%.2.2f”f,”,1100000.0.0/3/3));); System.out.println(String.format(“10000 / 33==%,.,2,..2f2″f,f””,1,0110000.0..0/03//3)3));));; System.out.println(String.format(“10000 / 33==%,1,100.2.2f”f”,,1100000.0.0/3/3)));; System.out.println(String.format(“255 = %hi ninhheexxaaddeecicmimala”,l”2, 525)5);)); System.out.println(String.format(“ASCII code 65 = %c”, 65));
— Sampleoutput
Ballanccee==101,0,000 10000/ / 3 =3333.3.33 10000/ / 3 =3,,333.3.33 1000// 3 = 3,333..33 255==fff ininhheexxadecimall ASCII code 65 = A
34

Chapter 5.
End
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
35