Page 448 - Introduction to Programming with Java: A Problem Solving Approach
P. 448

                414 Chapter 10 Arrays and ArrayLists
 /********************************************************************
*
Survivor.java
Dean & Dean
This class creates an ArrayList of survivors.
It randomly chooses one tribe member and removes him/her.
********************************************************************/
*
*
*
*
import java.util.ArrayList;
public class Survivor
{
}
// end Survivor
public static void main(String[] args)
{
}
int loserIndex;
String loser;
ArrayList<String> tribe = new ArrayList<String>();
tribe.add("Richard");
tribe.add("Jerri");
tribe.add("Colby");
tribe.add("Amber");
tribe.add("Rupert");
loserIndex = (inAt)p(aMagtho.ranPdoDmF() *Etnrihbea.snizce(e))r; loser = tribe.remove(loserIndex); System.out.println("Sorry, " + loser +
". The tribe has spoken. You must leave immediately.");
System.out.println("Remaining: " + tribe);
// end main
Typical Output:
 Sorry, Colby. The tribe has spoken. You must leave immediately.
Remaining: [Richard, Jerri, Amber, Rupert]
Figure 10.26 Survivor program
10.12 Storing Primitives in an ArrayList
As mentioned earlier, ArrayLists store references. For example, in the Survivor program, tribe is an ArrayList of strings, and strings are references. If you need to store primitives in an ArrayList, you can’t do it directly, but if the primitives are wrapped up in wrapper classes,6 you can store the resulting wrapped objects in an ArrayList. In this section, we show you how to do that.
  6 If you need a refresher on wrapper classes, see Chapter 5.




























































   446   447   448   449   450