Week 3: Classes and Objects in Java

Download Report

Transcript Week 3: Classes and Objects in Java

JAC444: Intro to Java
Arrays and Vectors
Tim McKenna
Seneca@York
Arrays in Java


arrays are objects
declare an array object reference


int[] iAr;
String[] strAr; // i.e. type[]
new creates an array object



specify the number of elements
iAr = new int[3]; strAr = new String[5];
auto initialization of array elements


primitive types: zero value
reference type: null
Arrays in Java



length: public final instance variable
iAr.length == 3; strAr.length == 5;
compile-time or runtime assignment of array
element values
java.util.Arrays – utility methods to



copy, search, sort, fill, convert toString
ArrayIndexOutBoundException
Example: ArrayDemo.java,
ArrayDemoStrings, ArrayDemoObjects
Two-Dimensional Arrays



an array of arrays (i.e. an array of objects)
an irregular / unbalanced array
Examples:
ArrayDemo2.java ArrayDemo3.java
Vector Class






Java package: java.util,
part of the Java Collection Framework
vector: like an array that shrinks and grows
vector stores generic object references
ArrayList class is like a Vector but is not
synchronized – less overhead for the JVM.
must be synchronized to support Threads
Vector Class

useful methods:





isEmpty(), size()
add(), remove(), insertElementAt()
get(), set()
methods using the object's equals() method:
contains(), indexOf(), lastIndexOf(), remove()
Examples: VectorDemoObjects.java,
VectorDemoCars.java, ParkingLot.java,
ParkingLotCars.java
Collections passing


do not give out references to your
collection – preserve encapsulation
java.util.Collections.unmodifiableXXX

allows modules to provide users with
"read-only" access to internal collections.