Java - Array

java

https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
https://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html
https://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html

// declaring an array and initializing it
int[] scores = new int[]{0,1,2,3,4};
String[] students = new String[10];
String[] strHeaderNames = { "USERSID", "LOGINID", "FIRSTNAME", "LASTNAME", "WINDOWS CREDENTIAL"};

// Creates an array of 12 elements
int months[] = new int[12];
int months[] = {1,2,3,4,5,6,7,8,9,10,11,12};

int[] scores = new int[]{0,1,2,3,4};
scores[0]
scores.length
private Dog[] list = new Dog[5];  // array of objects

// This method accept one argument which is an array of int
public static void change(int x[]) { ... }

// 2D arrays:
int[][] matrix = { {1,2,3}, {4,5,6} };
int[][] matrixA = new int[5][6];
matrixA = new int[3][]; // fine
// matrixA = new int[][5]; // compilation error
// matrixA = new int[][]; // compilation error
String[][] names = {
    {"Mr. ", "Mrs. ", "Ms. "},
    {"Smith", "Jones"}
};
int[][] matrix1; // Recommended
int[] matrix2[]; // legal but not readable.  Avoid
int x[][] = {{8,9,10,11}, {12, 13, 14, 15}}; // creates a 2 dimensional arrays and initialize its value
void display(int x[][]) { ... } // This method accept one argument which is a two dimensional array of integers

// Each row in a 2D array can have different length.  This is called a ragged array

// Accessing an array
scores[1]

// Accessing a two dimensional array
matrix[0][0]

// You can assign values to an array
matrix[0][0] = 1000;

// Arrays are immutable.  After we created the array, we cannot easily change the
// size of the array.  If we need to add an element to an array, we have to create
// a new array by copying the existing array.

// Copy an array
int[] arr2 = Arrays.copyOf(arr1, newArrayLength);
Arrays.copyOf(T[] original, int newLength)
Arrays.copyOf(U[] original, int newLength, Class<? extends T[]> newType)
Arrays.copyOfRange(boolean[] original, int from, int to)
Arrays.copyOfRange(T[] original, int from, int to)
Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)

// Sorting
numbers = Arrays.sort(numbers)
Arrays.sort(byte[] a)
Arrays.sort(byte[] a, int fromIndex, int toIndex)
Arrays.sort(Object[] a) // Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
Arrays.sort(Object[] a, int fromIndex, int toIndex)
Arrays.sort(T[] a, Comparator<? super T> c)
Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)

// Determine if two arrays are equal
Arrays.equals(marks, marks2); 
Arrays.equals(boolean[] a, boolean[] a2)

// Create a List from an array
Arrays.asList(arr);

// Search
Arrays.binarySearch(byte[] a, byte key);
Arrays.binarySearch(byte[] a, int fromIndex, int toIndex, byte key);
Arrays.binarySearch(T[] a, T key, Comparator<? super T> c)
Arrays.binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)

// Fill
Arrays.fill(marks, 90);
Arrays.fill(boolean[] a, boolean val)
Arrays.fill(boolean[] a, int fromIndex, int toIndex, boolean val)

Arrays.deepEquals(Object[] a1, Object[] a2) // Returns true if the two specified arrays are deeply equal to one another.
Arrays.deepHashCode(Object[] a) // Returns a hash code based on the "deep contents" of the specified array.
Arrays.deepToString(Object[] a)
Arrays.toString(scores);

Arrays.hashCode(boolean[] a)

// Looping over an array using the standard for loop
String[] toppings = {"Cheese", "Pepperoni", "Black Olives"};
int size = toppings.length;
for (int i=0; i < size; i++)
{
    System.out.println(toppings[i]);
}

int[] scores = {91, 92, 93, 94};
for (int score : scores ) { // enhanced for loop
  ...
}

// Using enhanced for loop to loop over 2 dimensional array
for (int[] array1:matrix) {
  for(int value : array1) {
    ...
  }
}

String[] splitArray = input.split("\\s+");

// The size of the array be changed dynamically.
// New arrays are always initialized with default values.  Default values for byte, short,  init,
// and long data types are 0.  Default values for float and double data types are 0.0.  Default 
// value for boolean is false.  Default values for objects are null.

// The Comparator interface defines two methods: compare( ) and equals( ).
// int compare(Object obj1, Object obj2)
// boolean equals(Object obj)

// int compare(Object obj1, Object obj2).  This method returns zero if the objects are equal.
// It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.

// By overriding compare( ), you can alter the way that objects are ordered. For example, 
// to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.

// boolean equals(Object obj).  The equals( ) method, shown here, tests whether 
// an object equals the invoking comparator.  obj is the object to be tested for equality. The method 
// returns true if obj and the invoking object are both Comparator objects and use the same ordering. 
// Otherwise, it returns false.  Overriding equals( ) is unnecessary, and most simple comparators
// will not do so.

class Dog implements Comparator<Dog>, Comparable<Dog> {
   private String name;
   private int age;
   Dog() {
   }

   Dog(String n, int a) {
      name = n;
      age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d) {
      return (this.name).compareTo(d.name);
   }

   // Overriding the compare method to sort the age 
   public int compare(Dog d, Dog d1) {
      return d.age - d1.age;
   }
}

public class Example {

   public static void main(String args[]) {
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy", 3));
      list.add(new Dog("Lacy", 2));
      list.add(new Dog("Roger", 10));
      list.add(new Dog("Tommy", 4));
      list.add(new Dog("Tammy", 1));
      Collections.sort(list);   // Sorts the array list

      for(Dog a: list)   // printing the sorted list of names
         System.out.print(a.getDogName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Dog());
      System.out.println(" ");

      for(Dog a: list)   // printing the sorted list of ages
         System.out.print(a.getDogName() +"  : "+ a.getDogAge() + ", ");
   }
}

What is the definition of Array?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

How can we access elements of an array?

Each item in an array is called an element, and each element is accessed by its numerical index.

int[] anArray = new int[10];
anArray[2] = 300;  // Assigning value 
System.out.println("Element at index 9: " + anArray[9]);

How can we create an array with 12 elements?

int months[] = new int[12];
int months[] = {1,2,3,4,5,6,7,8,9,10,11,12};

How can we declare a variable the represent an array?

byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

You can also place the brackets after the array's name:

// this form is discouraged
float anArrayOfFloats[];

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

How can we declare array of array?

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length.

class MultiDimArrayDemo {
    public static void main(String[] args) {
        String[][] names = {
            {"Mr. ", "Mrs. ", "Ms. "},
            {"Smith", "Jones"}
        };
        System.out.println(names[0][0] + names[1][0]);
        System.out.println(names[0][2] + names[1][1]);
    }
}
int[][] twoD = new int[4][5];

How can we copy one array to another array?

The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src, int srcPos,
                             Object dest, int destPos, int length)

The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
        char[] copyTo = new char[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}

How can we create an array of characters?

char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];

How can we use the copyOfRange method?

char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', 'd'};
char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);

The difference between System.arraycopy and java.util.Arrays.copyOfRange is that the copyOfRange method does not require you to create the destination array before calling the method, because the destination array is returned by the method.

The second parameter of the copyOfRange method is the initial index of the range to be copied, inclusively, while the third parameter is the final index of the range to be copied, exclusively. In this example, the range to be copied does not include the array element at index 9 (which contains the character a).

How can we search an array?

  • Searching an array for a specific value to get the index at which it is placed (the binarySearch method).

How can we determine if two arrays are equal?

Use Arrays.equals(a,b)

How can we fill an array with a specific value at every index?

Use Arrays.fill(arr, 20)

How can we sort an array?

This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.

If we have a list or an array of strings, how can we join them together?

import org.apache.commons.lang.StringUtils;
List myList = new ArrayList();
myList.add("...");
myList.add("...");
String result = StringUtils.join(myList , ",");

How can we declare an array of Strings?

String[] strHeaderNames = { "USERSID", "LOGINID", "FIRSTNAME", "LASTNAME", "WINDOWS CREDENTIAL"};

How can we loop over an array of strings? How can we initialize an array of strings?

String[] toppings = {"Cheese", "Pepperoni", "Black Olives"};
int size = toppings.length;
for (int i=0; i<size; i++)
{
    System.out.println(toppings[i]);
}

How can we split a string into an array?

String[] splitArray = input.split("\\s+");

How can we add element to a vector?

final Vector<Object> clearPreventableOrNotVector = new Vector<>();
clearPreventableOrNotVector.add(lUsersID);
clearPreventableOrNotVector.add(lEventID);

Vector<Object> params = new Vector<>();
params.add(profileID);
params.addAll(usersIDVector);

jt.update(sql, params.toArray());

How can we create a two dimensional array?

int[][] matrix1; // Recommended
int[] matrix2[]; // legal but not readable.  Avoid

marks = new int[5]
int marks2[] = new int[5];

Can the size of the array be changed dynamically?

Once an array is created, its size cannot be changed.

Can we create an array without defining its size?

No. We must specify the size of the array when we create it.

What are the default values in an array?

New arrays are always initialized with default values. Default values for byte,short, init, long data types are 0. Default values for float and double data types are 0.0. Default value for boolean is false. Default values for objects are null.

How can we loop through an array using the enhanced for loo?

for (int mark: marks) {
  System.out.println(mark);
}

How can we print the content of an array?

int marks[] = {25, 30, 50, 10, 5}
System.out.println(Arrays.toString(marks));

// Printing a 2D array
int[][] matrix = { {1,2,3}, {4, 5, 6}};
System.out.println(Arrays.deepToString(matrix));

How can we compare arrays?

Arrays are compared using the static equals method defined in the Arrays class. Two arrays are equal only if they have the same numbers in all positions and have the same size.

int[] numbers1 = { 1, 2, 3 }
int[] numbers2 = { 4, 5, 6 }

if (Arrays.equals(numbers1, numbers2)) {
}

How can we create a literal array?

int[] numbers = {1,2,3,4};

How can we sort an array?

numbers = Arrays.sort(numbers)

How can we copy an array?

int[] arr2 = Arrays.copyOf(arr1, newArrayLength);

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License