Arrays are a grouping data structure.
Arrays can be created using the new
keyword.
new
keyword causes Java to allocate a certain amount of memory for this array, even before it has been populated.char[] myFavoriteCharacters = new char[3];myFavoriteCharacters[0] = 'f';myFavoriteCharacters[1] = 'o';myFavoriteCharacters[2] = 'o';
In this case, Java knows that each char
value consumes 16 bits, so it reserves enough memory space for 3 of them.
The length of the array cannot be modified once memory has been allocated for an array of a specific length.
Arrays can be created using syntactic sugar
, or shorthand syntax that is converted to the longer-form automatically by Java upon compilation.
char[] myFavoriteCharacters = { 'f', 'o', 'o' };
Arrays can easily be made from text that contains a particular separator.
String myMessageToYou = "Don't worry about a thing";String[] words = myMessageToYou.split(" ");// now you have an array { "Don't", "worry", "about", "a", "thing" }
Arrays can easily be made from text that contains a particular separator.
String myMessageToYou = "Don't worry about a thing";String[] words = myMessageToYou.split(" ");// now you have an array { "Don't", "worry", "about", "a", "thing" }
You can also use regular expressions syntax to split by one of several separators:
String myMessageToYou = "Don't, worry?about-a .thing";String[] words = myMessageToYou.split("[ ,?-.]+");// now you have an array { "Don't", "worry", "about", "a", "thing" }
The length
property of any array counts its members.
Scanner scn = new Scanner(System.in);String[] veggies; // reference to an as-yet unallocated arrayint num = 0;while (num < 1) { System.out.println("Enter your favorite vegetables, separated by commas: "); String response = scn.nextLine(); veggies = response.split(","); // array is now allocated and populated num = veggies.length;}
The Arrays utility class is part of the Java API
import java.util.Arrays
Arrays.toString()
prints out the contents of the array inelegantly.
String[] arrVar = { "hello", "and", "good", "morning" };String contents = Arrays.toString(arrVar); // -> "[hello,and,good,morning]"
Arrays.toString()
prints out the contents of the array inelegantly.
String[] arrVar = { "hello", "and", "good", "morning" };String contents = Arrays.toString(arrVar); // -> "[hello,and,good,morning]"
... and for multi-dimensional arrays, use .deepToString()
:
String[][] arrVar = { {"hello", "world"}, {"goodbye", "world"}}; // a two-dimensional arrayString contents = Arrays.deepToString(arrVar); // -> "[[hello,world],[goodbye,world]]"
Arrays.equals()
determines whether two arrays have the same set of values:
String[] arrVar1 = { "hello", "and", "good", "morning" };String[] arrVar2 = { "hello", "and", "good", "morning" }; // a separate array with the same values as arrVar1 but at a different location in memoryboolean sameValues = Arrays.equals(arrVar1, arrVar2); // -> true!
Arrays.equals()
determines whether two arrays have the same set of values:
String[] arrVar1 = { "hello", "and", "good", "morning" };String[] arrVar2 = { "hello", "and", "good", "morning" }; // a separate array with the same values as arrVar1 but at a different location in memoryboolean sameValues = Arrays.equals(arrVar1, arrVar2); // -> true!
... and for multi-dimensional arrays, use .deepEquals()
:
String[][] arrVar1 = { {"hello", "world"}, {"goodbye", "world"} }; // a two-dimensional arrayString[][] arrVar2 = { {"hello", "world"}, {"goodbye", "world"} }; // a separate array with the same values as arrVar1 but at a different location in memoryboolean sameValues = Arrays.deepEquals(arrVar1, arrVar); // -> true!
Put them in order.
int[] arrVar = {134, 5, 3636, 34, 8};Arrays.sort(arrVar);// arrVar now holds {5, 8, 34, 134, 3636}
Put them in order.
int[] arrVar = {134, 5, 3636, 34, 8};Arrays.sort(arrVar);// arrVar now holds {5, 8, 34, 134, 3636}
It is also possible to sort a subset of the array:
int[] arrVar = {134, 5, 3636, 34, 8};int startIndex = 1;int endIndex = 4;Arrays.sort(arrVar, startIndex, endIndex);// arrVar now holds {134, 5, 34, 3636, 8}
Use Arrays.copyOf()
to make a clone:
int newArrLength = 10;Arrays.copyOf(arrVar, newArrLength); // copy into array of different length
Use Arrays.copyOf()
to make a clone:
int newArrLength = 10;Arrays.copyOf(arrVar, newArrLength); // copy into array of different length
... or .copyOfRange()
to clone a subset of the values in an array:
int startIndex = 0;int endIndex = 3;Arrays.copyOfRange(arrVar, startIndex, endIndex); // copy only a subset
Arrays.fill()
places default values into an array:
String defaultValue = "foo";Arrays.fill(arrVar, defaultValue);
The two most common ways of searching for a value within an array are:
Each has its advantages and disadvantages.
The most basic and reliable way to search for a value in an array is linear search, a.k.a. the brute-force approach, where we simply loop through each value in the array and compare it to the value we are looking for.
String[] words = {"good", "how", "morning", "are", "you"};String searchTerm = "morning";int pos = -1; // start out with a value that indicates we haven't found the searched-for value yetfor (int i=0; i < words.length; i++) { if (words[i] == searchTerm) { pos = i; // we have found the value at the position i }}// i -> 2
The most basic and reliable way to search for a value in an array is linear search, a.k.a. the brute-force approach, where we simply loop through each value in the array and compare it to the value we are looking for.
String[] words = {"good", "how", "morning", "are", "you"};String searchTerm = "morning";int pos = -1; // start out with a value that indicates we haven't found the searched-for value yetfor (int i=0; i < words.length; i++) { if (words[i] == searchTerm) { pos = i; // we have found the value at the position i }}// i -> 2
For a large array, this can be an inefficient way of searching, since we often have to loop through almost every value in the array before concluding the search.
The binary search algorithm more efficiently searches for a value in an array as follows:
The binary search algorithm more efficiently searches for a value in an array as follows:
This algorithm is only beneficial for arrays of values that can be sorted.
An example of a recursive implementation of a binary search algorithm.
public static int binarySearch(int arr[], int startPos, int endPos, int searchTerm) { if (endPos >= startPos) { int midPos = startPos + (endPos - startPos) / 2; // find the middle position of the array int middleValue = arr[midPos] // the value at the middle position if (middleValue == searchTerm) { // if the value we're looking for is exactly in the middle, return it return midPos; // return it if so } else if (searchTerm < middleValue) { // if the searchTerm is smaller than the middle value, it can only be present in the left half subset of the array return binarySearch(arr, startPos, midPos-1, searchTerm); // return the result of a binary search on only the left half } else { // otherwise, if the searchTerm is larger than the middle value, the searchTerm can only be in the right half return binarySearch(arr, midPos+1, endPos, searchTerm); // return the result of a binary search on only the right half } } return -1; // if we haven't yet returned anything, the value is not present in the array}
Binary search can be performed using the Arrays.binarySearch()
method:
int[] numbers = {2456, 35, 25986, 10, 12};int searchTerm = 10;int pos = Arrays.binarySearch(numbers, searchTerm); // -> 3
Due to the fixed-length nature of arrays, it is not possible to add or remove values to an array "on-the-fly".
Due to the fixed-length nature of arrays, it is not possible to add or remove values to an array "on-the-fly".
However, when it is desired to "add" a new value to an array, it is possible to:
Due to the fixed-length nature of arrays, it is not possible to add or remove values to an array "on-the-fly".
However, when it is desired to "add" a new value to an array, it is possible to:
Similarly, it is possible to "remove" a value from an array by:
An example of simulating "adding" new values on-the-fly to an array. Here we take an arbitrary number of inputs from the user and store whatever they enter into an array.
String[] veggies = new String[1]; // start with an array to hold just one valueScanner scn = new Scanner(System.in);boolean keepGoing = true;while (keepGoing) { System.out.println("Please enter a vegetable you like: "); String response = scn.nextLine(); veggies[veggies.length-1] = response; // add the user's response to the last spot in the array if (response.equals("stop")) { keepGoing = false; } else { String[] newVeggies = new String[veggies.length + 1]; // create a new array one bigger than the last for (int i=0; i < veggies.length; i++) { newVeggies[i] = veggies[i]; // copy each value from the old array to the new } veggies = newVeggies; // reassign the variable to point to the new longer array }}System.out.println(Arrays.toString(veggies));
A second solution to the problem of "adding" elements to an existing array is to use Apache Commons Lang's ArrayUtils
class.
.jar
file into a project's dependencies directory (often the lib
directory) and then importing it using import org.apache.commons.lang3.ArrayUtils;
int[] fibb = {0, 1, 2, 3, 5, 8};fibb = ArrayUtils.add(fibb, 13);System.out.println(Arrays.toString(fibb)); // outputs "[0, 1, 2, 3, 5, 8, 13]"
A second solution to the problem of "adding" elements to an existing array is to use Apache Commons Lang's ArrayUtils
class.
.jar
file into a project's dependencies directory (often the lib
directory) and then importing it using import org.apache.commons.lang3.ArrayUtils;
int[] fibb = {0, 1, 2, 3, 5, 8};fibb = ArrayUtils.add(fibb, 13);System.out.println(Arrays.toString(fibb)); // outputs "[0, 1, 2, 3, 5, 8, 13]"
The ArrayList
class, part of the java.util
package, is designed to give programmers a more dynamic array-like experience than the primitive arrays can do.
ArrayList
does not have a fixed lengthThe ArrayList
class, part of the java.util
package, is designed to give programmers a more dynamic array-like experience than the primitive arrays can do.
an ArrayList
does not have a fixed length
an ArrayList
can have new members added to it at any time
The ArrayList
class, part of the java.util
package, is designed to give programmers a more dynamic array-like experience than the primitive arrays can do.
an ArrayList
does not have a fixed length
an ArrayList
can have new members added to it at any time
an ArrayList
can have existing members removed from it at any time
The ArrayList
class, part of the java.util
package, is designed to give programmers a more dynamic array-like experience than the primitive arrays can do.
an ArrayList
does not have a fixed length
an ArrayList
can have new members added to it at any time
an ArrayList
can have existing members removed from it at any time
ArrayList
is not a primitive data type or data structure in Java - it is not built into the language as a native type
The ArrayList
class, part of the java.util
package, is designed to give programmers a more dynamic array-like experience than the primitive arrays can do.
an ArrayList
does not have a fixed length
an ArrayList
can have new members added to it at any time
an ArrayList
can have existing members removed from it at any time
ArrayList
is not a primitive data type or data structure in Java - it is not built into the language as a native type
ArrayList
is a reference type, as are all non-primitive data types or data structures
ArrayList<String> veggies = new ArrayList<String>(); // initialize an ArrayList that will hold Stringsveggies.add("avocado"); // add avocado (a fruit) to our list of vegetablesveggies.add("tomato"); // add tomato (a fruit) to our list of vegetablesveggies.add("crispy lettuce"); // add crispy lettuce to our list of vegetablesveggies.add("ketchup"); // add ketchup (a sweetened condiment) to our list of vegetablesveggies.add("bacon"); // add bacon (an animal product) to our list of vegetablesveggies.remove("avocado"); // remove avocado from our list of vegetablesint pos = veggies.indexOf("ketchup"); // returns 3, since "ketchup" is at position 3String sweetStuff = veggies.get(pos); // returns "ketchup", which is at position 3
ArrayList<String> veggies = new ArrayList<String>(); // initialize an ArrayList that will hold Stringsveggies.add("avocado"); // add avocado (a fruit) to our list of vegetablesveggies.add("tomato"); // add tomato (a fruit) to our list of vegetablesveggies.add("crispy lettuce"); // add crispy lettuce to our list of vegetablesveggies.add("ketchup"); // add ketchup (a sweetened condiment) to our list of vegetablesveggies.add("bacon"); // add bacon (an animal product) to our list of vegetablesveggies.remove("avocado"); // remove avocado from our list of vegetablesint pos = veggies.indexOf("ketchup"); // returns 3, since "ketchup" is at position 3String sweetStuff = veggies.get(pos); // returns "ketchup", which is at position 3
ArrayList
class.An example of adding new values on-the-fly to an ArrayList
. Here we take an arbitrary number of inputs from the user and store whatever they enter into an ArrayList
.
ArrayList<String> veggies = new ArrayList<String>(); // create a blank ArrayListScanner scn = new Scanner(System.in);boolean keepGoing = true;while (keepGoing) { System.out.println("Please enter a vegetable you like: "); String response = scn.nextLine(); if (response.equals("stop")) { keepGoing = false; } else { veggies.add(response); // add what the user entered into the ArrayList }}System.out.println(veggies);
An example of adding new values on-the-fly to an ArrayList
. Here we take an arbitrary number of inputs from the user and store whatever they enter into an ArrayList
.
ArrayList<String> veggies = new ArrayList<String>(); // create a blank ArrayListScanner scn = new Scanner(System.in);boolean keepGoing = true;while (keepGoing) { System.out.println("Please enter a vegetable you like: "); String response = scn.nextLine(); if (response.equals("stop")) { keepGoing = false; } else { veggies.add(response); // add what the user entered into the ArrayList }}System.out.println(veggies);
Compare this to performing the same task using primitive arrays.
Some textbooks and online discussions say, "Java is a 'pass by value' language!" What does this mean?
When a value type (e.g. a primitive data type value) is passed as an argument to a function, the situation is straightforward.
Take the following example:
public static void doSomething(int x) { x = 10;}public static void main(String[] args) { int x = 5; doSomething(x); // the value 5 is passed to the function System.out.println(x);}
The output of the above program is 5
, since the local variable within the main function is never reassigned to refer to anything other than 5.
doSomething()
is invoked and passed a copy of the value 5
(the value the main function's local variable x
).doSomething()
creates its own local parameter variable x
which refers to this value, 5
.doSomething()
reassigns its local variable x
to refer to 10
instead.doSomething()
completes and control flows back to the main method, where the main method's local varible x
still is assigned the value 5
.When a reference type (e.g. an array or object) is passed as an argument to a function, the situation is straightforward.
public static void doSomething(int[] x) { x = {25, 30, 35}; // the local variable is re-assigned to point to a different memory address}public static void main(String[] args) { int x[] = {5, 10, 15, 20}; doSomething(x); // the memory address of the array is passed to the function System.out.println( Arrays.toString(x) );}
The output of the above program is [ 5, 10, 15, 20 ]
, since the local variable within the main function is never reassigned to refer to anything other than that array, and that array has never had its contents modified.
doSomething()
is invoked and passed a copy of the memory address of the array referred to by the main method's variable x
(the "value" the main function's local variable x
).doSomething()
creates its own local parameter variable x
which refers to this "value" - the memory address of that array.doSomething()
reassigns its local variable x
to refer to the memory address of a different array instead.doSomething()
completes and control flows back to the main method, where the main method's local varible x
still is assigned the "value" of the memory address of the original array.When an array or an object is passed as an argument to a function, the situation is a bit less straightforward.
But consider the following example:
public static void doSomething(int[] x) { x[2] = 555; // the third spot within the array is re-assigned to refer to a different integer}public static void main(String[] args) { int x[] = {5, 10, 15, 20}; doSomething(x); // the memory address of the array is passed to the function System.out.println( Arrays.toString(x) );}
The output of the above program is [ 5, 10, 555, 20 ]
, since the local variable within the doSomething function is an alias of the variable within the main function - they both refer to the same array in the same memory location and that array's inner values have been modified.
The phrase, "Java is a 'pass by value' language is thus a bit confusing.
The trick to this is that the references are themselves passed as values - the value being the integer memory address at which the array or object resides.
You now have a basic understanding of arrays in Java.
Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
Number + Return | Go to specific slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
t | Restart the presentation timer |
?, h | Toggle this help |
Esc | Back to slideshow |