Saturday, January 12, 2013

1/12/13 Array Lists

A few posts ago, you learned about Arrays. The one major disadvantage to using an array is that it has a fixed size, so you need to know how many elements you will need before you create it. An arraylist is basically an array that's size can fluctuate as you use it. In this post, I will teach you how to do basic functions with arraylists.

To start of, you will need to create an arraylist. To do this, you would type:

Arraylist <Type> name = new Arraylist<Type>();

Where name is its name, and type is the data type that you want to use. When entering your data type, you will need to capitalize it . This is because you are filling the arraylist with an object that acts as the primitive data type that it represents (for an int, the object is called Integer). Fortunately, these objects can be used just like you use the primitive data type that they represent. This constructor will create an arraylist that has 10 indexes, all filled with their default value. To delete an index, you would type:

name.remove(index);

This would remove the index index from the arraylist name. After it is removed, all the other indices shift down to fill in the gap. If you are trying to go through every index in an array and delete some of them, you would need to re-check the deleted index, because the next element has shifted to that index. To add a value to the arraylist, you would type:

name.add(index, object);

This will add object at index index. If you just put object inside of the parentheses, it will be put in index 0. This will cause all the latter indices to shift up one to make space for the new one. Now that you know how to add and remove indices, you will need to return elements from your arraylist. To do this, you would type:

name.get(index);

This will return the index index from arraylist name. As you may think, to set the value of an index, you would type:

name.set(index);

There is one more arraylist method that I will teach you, the size method. Unlike other things, arraylists use a size method instead of a length one. To find the size of an arraylist, you would type:

name.size();

I hope that you learned a thing or two about java, and feel free to ask me if you have any questions about anything that I posted in any of my articles!

No comments:

Post a Comment