Friday, 9 September 2011

Java: Arrays III

    More arrays, woo!
    If you have the JDK, you can find a class named "Arrays" inside the "java.util" package. To use this, you need an import at the top of your code:

import java.util.Arrays;

    This tells the computer to import the class at that location. This class allows you to sort, search through, or do many other things with an array. For example, say you have an array as follows:

exArray = [ 1, 5, 4, 6, 2 ]

To sort this, you would, with Arrays imported, type:

Arrays.sort( exArray );

And would get:

exArray = [ 1, 2, 4, 5, 6 ]

There's much more in terms of what you can do with this included class, most of which you can find out either by use of your IDE ( Netbeans shows you functions as you type), or by reading the documentation available on the Oracle website. Not much else I can see in here is universally useful, except the toString method.


Will provide you with the string representation of the array in question, as I've shown above ( "[1, 2, ...]" ), without changing the actual array. Great stuff.

    So now what, that we have a bunch of functionality for our arrays? What if we need something more complex. Say, an array within an array. Well, I'm mentioning it, so you've probably already guessed it's possible. These are known as multi-dimensional arrays. All the arrays I've shown you thus far are 1 dimensional arrays, but to make 2 dimensional, just add another set of brackets to the initialization (As many as you want dimensions).

int[][] twoDArray = new int[3][5];

    This, as you might assume, creates a 3x5 array. You can access specific cells the same way you would in a normal array, but I don't see too much use for these multi-dimensional arrays for small projects.

   For ease of creating arrays, there are a couple of shortcuts. Instead of creating an array of length 10 then individually filling up each cell, you can simply type:

int[] exArray = { 1, 1, 2, 3, 5 } //Curly braces!

...and for 2-d arrays and up, you just put the arrays within the arrays, as you would expect.

    That's it for tonight. Follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us.     
     Mostly me, since he put me in charge of new uploads.

1 comment: