Array
An array structure is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of a single type. Instead of declaring individual variables, such as number0
, number1
,..., number99
, you declare one array variable numbers
and use numbers[0]
, numbers[1]
, ..., numbers[99]
to represent individual variables. The first element of array is at an index of 0
.
Following is a list of some of the common methods that arrays have:
- public static int binarySearch(Object[] a, Object key): Searches the specified array for the specified value using the binary search algorithm. The array must be sorted prior to calling this method. This returns the index of the search key, if it is contained in the array; otherwise it returns
(–(insertion point + 1))
.
- public static boolean equals(long[] a, long[] a2): Returns true if the two specified arrays of
long
s are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. The same method could be used by other primitive data types (byte
, short
, int
etc.) also.
- public static void fill(int[] a, int val): Assigns the specified
int
value to each element of the specified array of int
s. The same method could be used by other primitive data types (byte
, short
etc.) also.
- public static void sort(Object[] a): Sorts the specified array of objects in ascending order according to the natural ordering of its elements. The same method could be used by primitive data types (
byte
, short
, int
etc.) also.
Example:
Write the following code in the /home/labex/project/arrayTest.java
file:
public class arrayTest
{
public static void main(String[] args){
// you can use new to initialize an empty array.
String[] nameArray1 = new String[5];
// fill the empty nameArray1 items with same name "abc"
java.util.Arrays.fill(nameArray1,"abc");
// the for loop can also be used to iterate an Array
for (String name:nameArray1){
System.out.println(name);
}
// you can use some value to initialize the array.
String[] nameArray2 = {"Candy", "Fancy", "Ann", "Ella", "Bob"};
// you can get the length of the array
System.out.println("Length of nameArray2: " + nameArray2.length);
// you can get value by index
System.out.println("The last item of nameArray2 is " + nameArray2[4]);
// sort an array object
java.util.Arrays.sort(nameArray2);
System.out.println("Sorted nameArray2 by alphabet:");
for(String name:nameArray2){
System.out.println(name);
}
}
}
Output:
Run the arrayTest.java
file using the following command:
javac /home/labex/project/arrayTest.java
java arrayTest
See the output:
abc
abc
abc
abc
abc
Length of nameArray2: 5
The last item of nameArray2 is Bob
Sorted nameArray2 by alphabet:
Ann
Bob
Candy
Ella
Fancy