Showing posts with label arrays. Show all posts
Showing posts with label arrays. Show all posts

Saturday, 10 September 2011

Java: Container Classes

    So, as amazing as arrays are, and with all we can do with them, they`re still generally inflexible. Remember how, when creating a  new array, we specify its size? Well, that can't be changed. Bummer. And have fun if you want to wedge an element in between 2 existing elements, preserving all 3, or even altogether removing elements from the array (At best you can change the value to a 0, or something similar). So what do we do about this? The JDK has our back (again)!

    A common type of container class is the ArrayList, which can be used as an array, but with added functionality, meaning the programmer need not implement such methods for him/herself. This can be found in "java.util.ArrayList", so import that at the start of your code.

ArrayList<String> myArrayList = new ArrayList<String>();


    In this creation of an array list, we see some new info. First, the type the array list holds follows ArrayList in angle brackets. Great. It's worth noting at this point that you can't use primitive types (int, double, float, char. Essentially the datatypes that aren't capitalized.), but you can use Integer, Double, Boolean, etc. Another point we see is that there's no mention of size. The list starts off with no elements and then more are added later.

    From here, you can see, using your IDE, what kind of functionality the list has. In Netbeans, just type "myArrayList." (no quotes, or spaces), and it should present you with a bunch of functions you can apply to it, as well as the parameters each one takes. For instance, there are 2 "add" functions. One of them simply takes 1 parameter, of whatever type the array list is. This function just adds the parameter to the end of the array list. The other, which is used if you place 2 parameters when calling the method, takes as the first parameter the index where you want to place the element, which is the second parameter. It moves the element currently at that index, and any higher ones to the right by one. The final result of this is your element is squeezed in.

    If you instead want to get all values in the array list, simply print it. If you want a specific element, use the "get" method. And if you want to replace an element, use set.


 myArrayList.add("Hello");
System.out.println( myArrayList );
System.out.println( myArrayList.get(0) );
myArrayList.set(0, "Greetings or something");
System.out.println( myArrayList.get(0) );


    The above should give you an output of:



[Hello]
Hello
Greetings or something


    If you have trouble seeing why, or you don't get that output, let me know!






    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.

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.

Arrays.toString(exArray);


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.

Thursday, 8 September 2011

Java: Arrays II

    Let's start off with the foreach loop today. Remember yesterday, when filling out the elements of the array, we had a for loop to iterate over each element? Well, while that's a perfectly reasonable method to do so, and in fact, the method I personally prefer, there's a separate way to do this, known as the foreach loop.


    public static void main(String[] argv) {

        int[] exampleArray = new int[3];
        exampleArray[0] = 1;
        exampleArray[1] = 2;
        exampleArray[2] = 3;//just doing it this way since the for loop is as many lines for such a short array.

        int sumOfElements = 0;

        for ( int currentValue : exampleArray ) {
            sumOfElements += currentValue;
        }
        
        System.out.println(sumOfElements);
    }

    The purple bit is the foreach loop, it just takes each integer (in this case) inside the array provided, and performs the loop body on it. Simple stuff, makes for loops easier when iterating over entire arrays.

    As with basically anything else, you can use arrays as return values as well as parameters, but keep in mind that the pointer to the array is used in both cases. This means you cannot return an array, and print it out, expecting to see all the elements within, but you can call an index of the returned value.

public int[] arrayFunction() {
    // calculate array elements etc.
    return integerArray;
}


int[] exampleArray = arrayFunction();


System.out.println(exampleArray); //This is useless, you'll get a seemingly random assortment of characters that are used to tell the computer where to look in memory to get the array


System.out.println( exampleArray[ someIndex ]; //This is good, and useable!






This is it for tonight. Follow, comment, share etc. See you tomorrow!

Wednesday, 7 September 2011

Java: Containers (Arrays)

    Today, we learn about arrays! This is a very basic container type, directly integrated into Java. They hold collections of values (elements of the array), all of which must be the same type (That is, any type, as long as its consistent).
    Arrays are contiguous sequences of variables, where each variable contains a single value. The array has its overall name as defined by the programmer who created it, with each element being accessed through the array name, followed by the index of the desired element in square brackets. Since programmers count from 0, an array of 10 integers would be indexed from 0-9.

int[] exampleArray = new int[10];

    The above code creates an integer array ( int[] ), names it, then specifies its length ( int[10] ), 10.  String[] and whatever other class you want can be used instead of int, but int is easier to type, so that'll remain my examples.  

    Now to fill this array variable with actual values!

for ( int i = 0 ; int < exampleArray.length ; i++ ) {
    exampleArray[ i ] = i + 1;
}

    This should fill our array with the numbers 1 - 10, if you have trouble understanding the code, leave a comment below. You can now access whichever element you want by typing out exampleArray followed by whichever index you want. Be warned, you can't just print out the array using:

System.out.println(exampleArray);

...since this will return the pointer to the array, not the elements within. Pointers come later, as does more posting. Comment, follow, share, what have you, and see you tomorrow, hopefully!