JAC 444 Intro to Java Arrays and Vectors

  • Slides: 7
Download presentation
JAC 444: Intro to Java Arrays and Vectors Tim Mc. Kenna Seneca@York

JAC 444: Intro to Java Arrays and Vectors Tim Mc. Kenna Seneca@York

Arrays in Java n n arrays are objects declare an array object reference ¡

Arrays in Java n n arrays are objects declare an array object reference ¡ n int[] i. Ar; String[] str. Ar; // i. e. type[] new creates an array object ¡ ¡ ¡ specify the number of elements i. Ar = new int[3]; str. Ar = new String[5]; auto initialization of array elements n n primitive types: zero value reference type: null

Arrays in Java n n n length: public final instance variable i. Ar. length

Arrays in Java n n n length: public final instance variable i. Ar. length == 3; str. Ar. length == 5; compile-time or runtime assignment of array element values java. util. Arrays – utility methods to ¡ n n copy, search, sort, fill, convert to. String Array. Index. Out. Bound. Exception Example: Array. Demo. java, Array. Demo. Strings, Array. Demo. Objects

Two-Dimensional Arrays n n n an array of arrays (i. e. an array of

Two-Dimensional Arrays n n n an array of arrays (i. e. an array of objects) an irregular / unbalanced array Examples: Array. Demo 2. java Array. Demo 3. java

Vector Class n n n Java package: java. util, part of the Java Collection

Vector Class n n n Java package: java. util, part of the Java Collection Framework vector: like an array that shrinks and grows vector stores generic object references Array. List class is like a Vector but is not synchronized – less overhead for the JVM. must be synchronized to support Threads

Vector Class n useful methods: ¡ ¡ n is. Empty(), size() add(), remove(), insert.

Vector Class n useful methods: ¡ ¡ n is. Empty(), size() add(), remove(), insert. Element. At() get(), set() methods using the object's equals() method: contains(), index. Of(), last. Index. Of(), remove() Examples: Vector. Demo. Objects. java, Vector. Demo. Cars. java, Parking. Lot. Cars. java

Collections passing n n do not give out references to your collection – preserve

Collections passing n n do not give out references to your collection – preserve encapsulation java. util. Collections. unmodifiable. XXX ¡ allows modules to provide users with "read-only" access to internal collections.