3 Arrays Flashcards
List ways to write a one dimensional array
int[] numbers2 = new int[] {42, 55, 99}; int[] numbers2 = new int[3]; int[] numbers2 = {42, 55, 99}; Anonymous array the brackets can be before or after the name and space is optional int[] numAnimals; int [] numAnimals2; int numAnimals3[]; int numAnimals4 [];
With a reference. Bugs is another array.
String [] alias = bugs;
Describe multiple declarations in one line with arrays
int[] ids, types; Makes 2 arrays of type int because [] are on the left.
int ids[], types; Makes 1 array of type int and 1 int. It doesn’t make two arrays because the brackets are on the right and associated to just the one reference.
What is the import for arrays?
import java.util.* // import whole package including Arrays import java.util.Arrays; // import just Arrays or There is one exception, although it doesn’t come up often on the exam. You can write java.util.Arrays every time it is used in the class instead of specifying it as an import.
How can an array be sorted?
Arrays.sort(); The reference to the array goes in as a prarameter. Arrays.sort(myArray);
Just put that statement on a line and it saves the sorted array. You don’t assign it to anything like new arrary =
Arrays.sort(myArray) //WRONG
Beware that Strings sort in alphabetical order so
{10, 9, 100} will sort 10, 100, 9.
What is a binary search?
If an array is already sorted, binary search can be used to determine the index of a particular target.
A negative number is where the index would be if the number was in the sorted array, then made minus.
Target element found in sorted
array
Index of match
Target element not found in
sorted array
Negative value showing one smaller than the
negative of index, where a match needs to be
inserted to preserve sorted order
Unsorted array A surprise—this result isn’t predictable
int[] numbers = {2,4,6,8};
4: System.out.println(Arrays.binarySearch(numbers, 2)); // 0
System.out.println(Arrays.binarySearch(numbers, 1)); // -1
7: System.out.println(Arrays.binarySearch(numbers, 3)); // -2
8: System.out.println(Arrays.binarySearch(numbers, 9)); // -5
What does it mean when a binary search of an array returns a negative number?
A negative number is where the index would be if the number was in the sorted array, then made minus.
What happens if binary search is used on an unsorted array?
The results are unpredictable.
Are the brackets [ ] ALWAYS needed on BOTH sides of the equals sign (left and right sides)?
No
int[] numbers2 = {42, 55, 99}; // OK
int[] numbers2 = new int[] {42, 55, 99}; // legal NOT necessary
What is an anonymous array?
the type and size is not specificed on the right side
int[] numbers2 = {42, 55, 99};
Does .equals look at the elements inside two arrays being compared?
No. It looks to see if referring to same object.