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.

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:

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.

1 comment: