1z0-808 Oracle Java SE 8 Programmer – Arrays part 2
- Multi-Dimensional Arrays
So far we’ve been looking at singledimensional arrays and that’s predominantly what you’re going to be using. Java does, however, support multidimensional arrays. The way that we create this is that each dimension will have its own set of square brackets. So here’s an example of creating a twodimensional array. Notice that we’ve got two sets of square brackets on the left side as well as two sets on the right. What we’re saying is this is a two dimensional array. Now the way that multi dimensional arrays work is that every single dimension except for the last one stores an array, whereas the last dimension are going to store the actual values.
So let’s look at populating this array. What we’re saying is that the first dimension of the string is going to store five different arrays. And that’s going to have the number zero, the number one, the number two, three, four, all the way from zero to four. The second dimension is going to be an array that stores two values. So zero and 10 and one for each dimension. And then when we’re going to set the values, we just have to include both dimensions. So we can say specifically what element are we setting? So this is kind of like a phone book. We can store five different people.
And when we store the phone numbers, we can store two parts, right? We can store two different pieces of information. So the name and the phone number. So array zero can have two different pieces of information, zero and one. Array one can also have two pieces of information, zero and one and so on. So zero zero is the name Paul. Zero one is the phone number. Now we’ll go to the next array. 10 is Scott and one one is Scott’s phone number and so on. We can do the literal initialization like we did before. It just looks a little different. So first of all, we have the single set of brackets to represent the first dimension.
And then what we’re doing is listing each array inside of it. So in this case, we have an array with two elements, another array with two elements, and another array with two elements. So if we were to think about what is the length of the first dimension? Well, there are three elements in that first dimension. So if I said what is array length? Notice I’m not putting any specific element here, then it’s going to give me the length of the first dimension, which would be three. But then in this case I’m asking for the length of array zero. Well, that’s going to be this array that’s inside of the second dimension. So that one will have a length of two.
Again, notice how each element of the outer array is an array and each element of the inner array is the data. And you can get kind of crazy with this. We can have many, many arrays, or I should say many, many dimensions in our arrays. Let me show you an example of a four dimension array. So it says four square brackets and then what each of the different sizes is. So that means that in the first dimension we have two arrays. And for each of those two arrays, in the second dimension they have two arrays and so on until you finally get to the very end where we can put three pieces of data for each of these different combinations.
If we were to think about this or examine it visually, it would look something like this. So as you can see, multi dimensional arrays can be really complicated. Imagine that I’m looking for I want to get the value of string 0101. So zero here, 10 one. What would that be? Well, this would be zero, this blue. And then one would be this yellow because this would be the yellow. Zero over here, the yellow one. And then zero would be the first pink thing here. And then one would be the second element inside. So right here, that’s the index of 0101. The good news is you’re not going to have to spend that that much time creating such a raise. But just note that it is possible.
- Sorting and Searching Arrays
The Java API includes a class that will help us with all sorts of tasks, including sorting and searching. It’s in the Java util package. It’s called arrays, it’s plural arrays. And that’s going to help us with all sorts of searching and sorting and filling and all sorts of stuff. After this lecture, I do recommend that you go to the API and become familiar with what it offers. In this lecture, though, we will look at some of the more popular methods, starting with arrays. Sort. So sort allows you to pass in some comparison instructions. Sort will take care of the complex logic of going through and sorting everything, but you can pass in some instructions of how things should be sorted.
This is done through an object called a comparator and that’s something that we’ll talk about in an upcoming section. So we’ll hold off on the comparator for right now. But even if you don’t pass in a comparator, if you’re dealing with primitives, then what’s going to happen is it’s going to use the natural ordering to sort it, which in this case would be the Unicode value. So the precedence would be all numbers have a higher precedence than capital letters and capital letters have a higher precedence than lowercase letters. So here’s an example of running the sort. I’ve got an array called letters.
We’ve got DAC and b. These are primitive chars and we call arrays sort. Notice it’s a static method, so I don’t need to instantiate arrays and we pass in the letters array. At that point it will be organized as A-B-C and D. And that sets us up for the next method, which is binary search. The purpose of binary search is that we give it an array, we give it the thing that we’re trying to find and then it returns the index of where we can find it at. Now, an array must be sorted for a binary search to work. So you always run the sort first, but after that we can run the arrays. Binary search, we pass in the array, we pass in the thing that we’re looking for.
In this case a char called C. And then that’s going to return the index of where it’s located in the array. It’s a little odd, but if the search value cannot be found, then what it does is it returns an int. And this is a little complex. This is something you’re going to probably want to write down, especially if you’re taking the exam. But what it will do is it’ll try to figure out what is the index where it should have been, where would I have expected to find it. And then what it does is it adds one more to that and turns it into a negative number. So let’s look at an example. Our letters array had A-B-C and D. Now imagine that I’m trying to find E, so it would probably expect to find E at an index of four.
What it’ll do, since it doesn’t find E, is it’ll take four and it’ll add one to that, so that’s five, and then it’ll turn it into a negative number. So rather than getting a normal index, we would see an index of negative five. There is a method to help us fill all the elements of an array with a single value. That’s called arrays fill. So here’s an example. We’re taking letters and we’re filling every open element, or rather every element with the letter Z. This is example, of course, was for our array of chars. But the methods are overloaded and it can handle any type of an array.
- Common Array Mistakes
Let’s talk a little bit about some of the problems that you might run into with an array. The array syntax can be a little bit confusing. It’s a little different than Java objects. And as such, even experienced Java developers will occasionally run into problems. So we’ll talk about some of the more common coding mistakes that you might run into. Some of the mistakes that you run into are caught at compile time. And that’s actually great because that means that we can fix it before we even try running the program. Unfortunately, others are only found at runtime and so we’ll look at some of those as well.
So the first common mistake is really to forget that an array is zero index. So when we create an array, we don’t want to skip the first element. This is an example of a for loop that’s trying to loop through everything, but it left off the first element in the array. And it did that because it started with int j equals one. So really that should have been int j equals zero. Here’s a similar problem that’s related to counting. So we’re going to go a little too far past the array. Down here, the for loop. You can see now we’ve got the right starting point. We’re starting with j is equal to zero and we’re going to less than or equal to the staff dot length.
That’s a problem. Remember, it always has to be less than the length because we’re starting with a zero index. Make it really simple. Imagine that you’ve got an array that has three elements. So we have an index of zero, one and two. If you’re going to go all the way to the length of that array, that means you’re going to go to three. And there is no number three index in an array that will give you a runtime exception. It won’t be caught at compile time. It’s a runtime exception. It’s called Java lang array index out of bounds. We’ll talk a lot more about exceptions in the final section of this class.
Also remember that the length is a read only attribute and it’s not a method. So this is a common mistake, staff length, parentheses. Remember, parentheses means it’s a method and length is not a method that’s not available. So this won’t even compile. It’s not a surprising mistake to make because as soon as you start getting used to encapsulation, you’re going to start thinking, I don’t access fields directly, I don’t access these instance variables directly. I call a method. And this is one of the weird use cases where in fact it is a public attribute. You can access it directly. Also, in other classes there may be a method called length or a method called size.
And so that can start to throw you off a little bit as well. So just remember, with an array, it is a public read only attribute. Another issue that you might run into, but this is one the compiler will catch, is when you’re trying to declare a size in the wrong place. So here we’ve got int and we’re specifying 100 x. You don’t declare the size size in the reference variable, you declare it when you’re creating the array. So only in initialization can the array size be set. This is legal where we say new into 100, we can’t put the size in the reference variable.
- Varargs
As you write more and more Java programs, you’re inevitably going to run into a scenario where you need to have a method and that method will accept a parameter. But you don’t really know how many arguments should be passed in until runtime. You want to be able to accept a variable number of arguments. Well, we just learned about an array and that’s a great way to be able to pass in a variable number of arguments. Like for example, here’s a method method that says my method takes lots of ints and so we’re passing in an array of ints and we can then loop through that array using a for loop in this case specifically the for each loop and then do whatever we need to with the ints.
The great thing is that every time this method is invoked there may be a number of different ints. We just work with whatever is given to us that gives us some flexibility. The way that this would be invoked, if we look down below the code here, we would create our int array and then we would pass the array into that method. Now that works fine, that’s great. But there is an optional syntax to do the same thing and it’s called VAR Args. The syntax for VAR args is you specify what is the argument type and then you use an ellipsis which is just three dots. So here’s an example. My method takes lots of ints. Now I say int and what that means is that this method will take zero or more ints, whatever that type is.
The way that we work with the value once it comes in is the same way that we work with a regular array. So we’re just looping through here and going through all the different ints that were passed in. And the nice thing is that when we call this now we don’t have to create the array prior to passing it into the method. Notice that my method here. I just put a comma separated list of all my ints and another time that I call it I have a different set and a different number of ints and so on. So it’s a nice shorthand so that we don’t have to wrap our variable arguments in an array. So underneath the covers, Java is just treating this as an array. So we access it like it’s an array.
There is one limitation when we define a method that’s going to accept an array that can only occur once in a parameter list and it must always be placed at the end of the parameter list. So for example, let’s say we got a method that has some other arguments. In this case we’ve got a method where it takes in a string and a double. As you can see, the int variable arguments is at the very end. If I had that int in the middle or listed first, it wouldn’t compile as a side note it’s not common to see in code, but you can actually legally write the front door for our Java applications. The main method. Using this syntax you can say public static void main string args so that’s it VARGs are just an alternative syntax so that we can accept a variable number of arguments without having to wrap everything in an array.
- Arrays Lab
In the arrays lab, you’re going to create an array of my date objects that represent holidays. And then in the Order, what you’re going to do is make sure that none of the order dates are set to a holiday. This is all the instructions are found in lab 14, arrays in the resources. And if you have any questions, let me know.