Arrays

  • An array is a reference type
  • int[] or int[][] is an object
  • When you pass it as an argument, you pass a copy of the reference to the array.

Syntax

  • Java style is preferred
// C-style
int array[];
 
// Java-style
int[] array;

Creation

  • max size of array is slightly less than Integer.MAX_VALUE
// list of elements
int[] array = { 1, 2, 3, 4 };
 
// n = array length
int[] numbers = new int[n];
 
// new keyword with list of elements
var floatNumbers = new float[] { 1.02f, 0.03f, 4f };

Iteration

  • For each loop has limitations:
    • cannot access other indices values
    • cannot modify an array because the variable we use for iterations doesn’t hold the actual array element, only a copy
int[] squares = new int[5];
 
// for-loop
for (int i = 0; i < squares.length; i++) {
    squares[i] = i * i; // set the value by the element index 
}
 
System.out.println(Arrays.toString(squares)); // [0, 1, 4, 9, 16]
 
// for-each loop
for (var num:squares) {
    num = 50; // this does not modify the array
}
 
System.out.println(Arrays.toString(squares)); // [0, 1, 4, 9, 16]

Multi-dimensional arrays

  • You can have jagged array with each row having different columns
int[][] twoDimArray = {
        {0, 0},       // the length is 2
        {1, 2, 3, 4}, // the length is 4
        {3, 3, 3}     // the length is 3
};
 
 
System.out.println(foo instanceof int[][]);

Converting Arrays to ArrayList

  • Fixed size Array List:
    • Conversion allows arrays to be viewed as lists.
    • Conversion returns fixed size list
    • Adding and removing elements throw error
    • Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array.
  • Avoid Arrays.asList() since it is neither completely immutable nor mutable (since add not supported)
    • Use List.of() which creates immutable list
int[] arr = {1, 2, 3};
var myList = Arrays.asList(arr); // mutable and can cause side effects to arr
var myList2 = List.of(arr); // immutable
  • Independent ArrayList:
String[] stringArray = new String[] { "A", "B", "C", "D" }; 
List stringList = new ArrayList<>(Arrays.asList(stringArray));

Converting ArrayList to Array

List<String> strList = new ArrayList<>();
strList.add("abc");
strList.add("xyz");
strList.add("pqr");
strList.add("mno");
 
String[] strArr = strList.toArray(new String[strList.size()]);

Arrays class

  • Arrays contains helper utilities
  • Arrays.sort(T[], Comparator)
  • Arrays.sort(primitive[])
  • Arrays.fill(arr, value)
  • Arrays.copyOf(arr, newLength)
  • Arrays.binarySearch(arr, target)
  • Arrays.equals(arr1, arr2)
  • Arrays.deepEquals(arr1, arr2) — multi-dimensional array
  • Arrays.toString(arr)
  • Arrays.deepToString(arr) — multi-dimensional array
  • Arrays.stream(arr)
  • Arrays.asList(arr) — fixed size array