Array and ArrayList

  • Java has only 1-dimensional array. To create multi-dimensional array, you need to create array of reference to another arrays (array of array)
  • Class Arrays - utility static methods for Array
  • Class ArrayList - dynamically re-sizable array

Declaration

Create new array object holding 10 integers:

int[] array = new int[10];

Get length of array:

array.length

Declare and initializes an array:

int[] array = {32, 27, 64, 18, 95, 14, 90, 70, 60, 37};

Create new array with size determined at run-time:

final int ARRAY_LENGTH = 10; // constant
int[] array = new int[ARRAY_LENGTH]; // create array

Iterating Array

Using counter/index:

// add each element's value to total
for (int counter = 0; counter < array.length; counter++)
   total += array[counter];

Using no index:

// add each element's value to total
for (int number : array)
   total += number;

Passing an Array

  • Passing an Array is pass by reference
  • Passing an primitive type element is pass by value

Two-dimensional Array

Declare and initialize:

int[][] array1 = {{1, 2, 3}, {4, 5, 6}};        
int[][] array2 = {{1, 2}, {3}, {4, 5, 6}}; 

Variable-length Argument List

  • This allows method to accept any number of arguments
  • Behind the scene, this variable-length argument is an array object
   // calculate average
   public static double average(double... numbers)
   {
      double total = 0.0; 

      // calculate total using the enhanced for statement
      for (double d : numbers)
         total += d;

      return total / numbers.length;
   } 

Arrays Class Methods

// sort doubleArray into ascending order
Arrays.sort(doubleArray); 

// fill 10-element array with 7s
Arrays.fill(filledIntArray, 7); 

// copy array intArray into array intArrayCopy
int[] intArray = {1, 2, 3, 4, 5, 6};
int[] intArrayCopy = new int[intArray.length];
System.arraycopy(intArray, 0, intArrayCopy, 0, intArray.length);

// compare intArray and intArrayCopy for equality
boolean b = Arrays.equals(intArray, intArrayCopy);

// search intArray for the value 5
int location = Arrays.binarySearch(intArray, 5); 

ArrayList<T>

Initialize String ArrayList:

// create a new ArrayList of Strings with an initial capacity of 10
ArrayList<String> items = new ArrayList<String>(); 

Adding elements:

items.add("red"); // append an item to the list          
items.add(0, "yellow"); // insert "yellow" at index 0

Get length of ArrayList

items.size()

Remove elements:

items.remove("yellow"); // remove the first "yellow"
items.remove(1); // remove item at index 1

Look up for an element

items.contains("red")

ArrayList can be iterated using the same way as Array.


Revision #1
Created Sun, May 26, 2019 3:17 AM by Par
Updated Sun, May 26, 2019 3:53 AM by Par