Arrays

  • Rule 1: Array and List are not the same thing, not in Java.
  • Rule 2: Index starts at 0, that means if you created an array of length 10, there will not be an index 10 for your array.
  • Rule 3: You cannot resize the length of the array once it is created.
  • Rule 4: Index is always a positive number or zero, there is no negatie index.
  • Rule 5: You have to follow the above rules or tony will be sad.

Arrays are a datatype, to create an array, you will have to specify what kind of datatype this array holds, followed by square brackets. For example:

  • String array -> String[]
  • int array -> int[]
  • Object array -> Object[]

People usually get confused that arrays are type of its own. String is not the same as String[], they are two different datatypes.

There are three ways to instantiate an array, you will have to know all three of them. Let’s make an int array of size 5.

1. int[] arr1 = new int[5]; <-- notice the 5 indicates the size of this array.

This line of code will create an int array of size 5, The array will be pre-populated with default value of the type of the array. Because this is an int array, the default value will be a 0. 2. int[] arr2 = new int[] {0, 0, 0, 0, 0}; This will also create an int array with five zeros inside. 3. int[] arr3 = {0, 0, 0, 0, 0}; This is the easiest/straightforward way to initialize an array and assign values to it at the same time. However, there is a downfall to this approach. You HAVE TO define the variable and initialize using array literals as one statement if you want to use this approach. What that means is int[] arr4; arr4 = {1, 2, 3, 4, 5}; is NOT allowed.

If you want to know what value is in a specific index of the array, you can put an index in the square bracket and the code would return the value of the index specified(if valid index). In java, all index has to be positive or 0, index at -1 does not give you the last item of the array. For example, if you want to know what is at the 0th index of the array.

            System.out.println(arr[0]);

        

Similarly, if you want to assign a specific value to an array index, you have to access the index at the left hand-side and assign a value on the right hand-side. Like

            arr[0] = 10;
        

Notice that if you try to access an index that doesn’t exist, java will give you a runtime exception. Because of the nature of arrays, it is often used along with for loops. If you want to print out the content of the array. It is very tempting to do

          System.out.println(arr);
        

It compiles and runs fine, however, you get disappointed when you see [I@33q4u96 or some random crap in your output. This is happening because the variable only contains the memory address of the object and it would simply print the address if there is no toString() defined. For now, you only need to know that toString is a method that allows an object to have a String representation, if an object doesn’t have this method, it would print out useless stuff. So how do we print out the array? We will need to use a loop to iterate through the array and print it out manually. In order to achieve this, we will need one more information – the length of an array. You can achieve this by doing

            arr.length;

       

This will return you the length of the arr. Notice that there is no parenthesis after length. However, there is parenthesis if you are looking for the length of a String like

            String str = “test”;
            str.length();
        

This is one of the cases where you might say “wtf is java developers thinking when they wrote java”. So don’t get confused and make sure you do them right on test and homeworks.
Now we have all the information, we can continue with printing out the array. We will need to iterate through the array n times where n is the length of the array. Since index starts at 0, it is more straightforward if we start our for loop with 0. We construct the for loop as follows.

            int[] arr = … // some value that is not visible to us.
                for(int i = 0; i < arr.length; i++) {
                    System.out.println(arr[i]);
                }
        
Question: How do you generate a copy of an array?

Assume that we now have the following:

            int[] arr1 = {1, 2, 3, 4, 5}
        

How do we make a copy of the array? Let’s try the following:

                    int[] arr2 = arr;

        
//TODO add illustration here

This is called a shallow copy of the array. What we did is merely making the two variables point to the same object. Hence anyting I change on arr1 will also be changed on arr2. Let’s observe the following code.

            int[] arr1 = {1, 2, 3, 4, 5};
            int[] arr2 = arr1;
            arr1[0] = 9;
            for(int i = 0; i < arr2.length; i++){
                System.out.print(arr2[i]);
            }
        

The output of arr2 will be 9, 2, 3, 4, 5 even though we never changed the content of arr2 directly. Having an alias of an object is sometimes useful in programming, but it is not for copying array. The correct way of copying array is creating a new array with the same length, and then manually populate the content from the old array. Hence the following code:

            int[] arr1 = {1, 2, 3, 4, 5};
            int[] arr2 = new int[arr1.length];
            for(int i = 0; I < arr2.length; i++){
                arr2[i] = arr1[i];
            }