Why? Well, first of all, one can implement them in the same way they would use regular old arrays.
However, Array Lists give one a few useful abilities that separate them from the pack.
So how do you declare them?
Simple
You'll need to make sure that you have imported "Java.util.ArrayList"
If you're using an IDE such as Eclipse, then you'll probably get a notice and it will do it for you. IDE's are great like that, they do a lot of the work for you.
To declare an Array List you just follow these guide lines:
ArrayList <Object> myList = new ArrayList<Object>();
You can set the object you want the Array List to contain, not unlike regular arrays. Fill it with Strings, or create a custom class and fill it with that!
The best thing about Array Lists is that they are dynamically sized.
You can add and remove to them, which will update the size as you change it.
This differs from arrays where they must be of a fixed size.
If you want to add to an array you must create an entirely new array that copies everything over. Not the case with Array Lists.
Here is some sample code, creating an ArrayList and then adding to it.
Okay, so I've filled it with gibberish, but you get the idea.ArrayList <String> myStrings = new ArrayList<String();
myStrings.add("Funkadelic");
myStrings.add("Coolarific");
you can get the size of an ArrayList easily too. Not using .length as with arrays though!
myStrings.size();
If you wish to remove an element from the array, you simply do the following:
myStrings.remove(0);
This will remove the item at that index of the array list.
So there you have it. If you've ever wanted to be able to change the capacity of an array, here is your solution.
I am still experimenting with Array Lists. I intend to find out more about what else they can do. So keep your eyes peeled for updates in future blog posts.
Until then, array with you.
Apologies for that horrible pun.
No comments:
Post a Comment