Please enable JavaScript.
Coggle requires JavaScript to display documents.
Understanding Java Arrays (Structure of an array (Some examples (int ids[]…
Understanding Java Arrays
Structure of an array
int[] numbers = new int[3];
int[] numbers = new int[] {45, 55, 99};
shortcut
int[] numbers = {45, 55, 99};
valid statements
int[] numAnimals;
int [] numAnimals2;
int numAnimals3[];
int numAnimals4 [];
Some examples
int[] ids, types;
creates two array of type
int ids[], types;
create ids as array of int
create types as int
array of strings
String[] bugs
Store reference to string
bugs.equals(alias);//true
References are equals
In Objects the method equals verify the references equality
arrays keeps reference of objects.
Sorting
Sort elements in array
e.g int[] numbers = {6, 9, 1}
java.util.Arrays.sort(numbers);//array will be {1, 6, 9}
sort in crescent order
e.g. String[] strings = {"10", "9" "100"};
java.util.Arrays.sort(strings);//array will be {"10", "100", "9"};
sort in alphabetic order
Searching
Search an element in array only if array is already sorted
Arrays.binarySearch(array, element);
It looks for element inside of array and return its index
if array is not sorted, the result is unpredictable
Curious
binary search splits the array into two equals pieces and determines which half target it is. It repeats this process until only one element is left.
Varargs is normal array
Multidimensional arrays
creating
int[] [] vars1;//2D array
int vars2 [][]; //2D array
int[] vars3[]; //2D array
int[] vars4[], space[][]; // a 2D AND a 3D array
not valid
int[] array[] = new int[][2]; //Does not compile
int[][] array = new int[][]; //Does not compile
String[][] rectangle = new String[3][2];
rectangle[0][1] = "set"
int[][] differentSizes = {{1,4}, {3}, {9,8,7}};
An asymmetric multidimensional array
int[][] size = new int[1][];
size[0] = new int[2];
iteration loop
enhanced for
for(int[] inner : twoD)
for(int num : inner)
System.out.print(num + " ");
System.out.println();