Java Reference
In-Depth Information
Try This Yourself
Read that over and see if you can figure out what it will do when run.
Does it all make sense? Let's go through the code and see what's going on.
First, at
❶
there's the
new
to create a list that will hold
String
s. So far so good.
Next, starting at
❷
we're adding a couple of strings to this list, one at a time,
using the
List
function
add()
. With these added to the list, we can now try to
get some data out.
On the line at
❸
we're getting the third element of the list—by asking for the
list index of 2. Remember, it's zero-based counting, just like
Array
, which we
talked about earlier. The third element is the string
"a"
.
Next we check to see how many elements are in the list, using the function
size()
at
❹
, and it tells us there are four.
One of the advantages of an
ArrayList
over an
Array
is that you can easily add
and remove values—even in the middle of the list, as seen here on the line at
❺
, where we're using
add()
and passing in an index of 3. That will add this
value at index 3 in the list and move all the other values down one.
You can also remove values, read values, and so on, as much as you like. No
matter how we add or shuffle values around in the list, we can check to see
if a particular value is in the list without having to look through the whole
list, as with the call to
contains
that looks for the word
"is"
at
❻
. Cool, it's in
there. After that we'll try again with a value that
isn't
in there. And indeed,
the
contains
function returns false for
"kerfluffle"
.
You've seen how you could get a single value by index using the
get
function,
but what if you want to go through the list one by one?
You could use a
for
loop as we did with
Array
, but that's old-fashioned, ugly,
and error prone.
Instead, you can use a
for-each
construct. The statement
for(String value : listOf-
Strings)
acts like a
for
loop that iterates over the collection
listOfStrings
, and in
the body of the loop it will set the variable
value
to each entry as it goes
through. We first saw this back in
SkyCmd
.
Whew! That's a lot of explanation for a few short lines of code. But it's a
powerful idea, and we're going to use this in a plugin in just a bit.
Finally, what happens when we clear out the list entirely (at
❼
)? Not much
interesting, as it's empty now.