Java Reference
In-Depth Information
There's a lot more gunk in there than we've seen up to now. First of all, I've
called our new list myPlayerList . Note that funny syntax with the angle brackets,
< and > . You have to specify the kind of list you're making (twice, in fact).
Java 7 improves on this a little; you don't have to repeat it on the right-hand
side and you can say List<Player>whatever=newArrayList<>() . Also, in a small bit
of weirdness, notice that although it's List on the left, it's ArrayList on the right.
The reason for that is…because Java. (Okay, the reason is that List is the
parent and ArrayList is one particular child.) Moving on now. 2
With a list you've created, you can do a lot of fun things, like adding and
removing values from the list, retrieving values, and checking to see if a value
exists. Here's a bit of sample code:
ListPlay/src/listplay/ListPlay.java
public void listDemo(Player me) {
List < String > listOfStrings = new ArrayList < String >();
listOfStrings.add( "This" );
listOfStrings.add( "is" );
listOfStrings.add( "a" );
listOfStrings.add( "list." );
String third = listOfStrings.get(2);
me.chat( "The third element is " + third);
me.chat( "List contains " + listOfStrings.size() + " elements." );
listOfStrings.add(3, "fancy" );
boolean hasIt = listOfStrings.contains( "is" );
me.chat( "Does list contain the word 'is'? " + hasIt);
hasIt = listOfStrings.contains( "kerfluffle" );
me.chat( "Does the list contain the word 'kerfluffle'? " + hasIt);
// Print out each value in the list
for ( String value : listOfStrings) {
me.chat(value);
}
listOfStrings.clear();
me.chat( "Now it's cleared out, size is " + listOfStrings.size());
hasIt = listOfStrings.contains( "is" );
me.chat( "List contains the word 'is' now is " + hasIt);
}
2. “Because Java” is a bit of an Internet joke; see http://www.theatlantic.com/technology/archive/
2013/11/english-has-a-new-preposition-because-internet/281601 for details.
 
 
 
Search WWH ::




Custom Search