Here is a complete program that manipulates a list.
0171: // // ExamineList.java 0172: // Read a list of people from a file, output the list, and then examine it. 0173: // Barry Cornelius, 6th February 2000 0174: import java.util. ArrayList; 0175: import java.io. BufferedReader; 0176: import java.io. FileReader; 0177: import java.io. InputStreamReader; 0178: import java.io. IOException; 0179: import java.util. Iterator; 0180: import java.util. List; 0181: public class ExamineList 0182: { 0183: public static void main(final String[] pArgs) throws IOException 0184: { 0185: if (pArgs.length!=1) 0186: { 0187: System.out.println("Usage: java ExamineList datafile"); 0188: System.exit(1); 0189: } 0190: final List tList = new ArrayList(); 0191: // read a list of people from a file 0192: final BufferedReader tInputHandle = 0193: new BufferedReader(new FileReader(pArgs[0])); 0194: while (true) 0195: { 0196: final String tFileLine = tInputHandle.readLine(); 0197: if (tFileLine==null) 0198: { 0199: break; 0200: } 0201: final Person tFilePerson = new Person(tFileLine); 0202: tList.add(tFilePerson); 0203: } 0204: // output the list that has been read in 0205: final Iterator tIterator = tList.iterator(); 0206: while (tIterator.hasNext()) 0207: { 0208: final Person tIteratePerson = (Person)tIterator.next(); 0209: System.out.println(tIteratePerson); 0210: } 0211: // ask the user to examine the list 0212: final BufferedReader tKeyboard = 0213: new BufferedReader(new InputStreamReader(System.in)); 0214: while (true) 0215: { 0216: System.out.print("Person? "); 0217: System.out.flush(); 0218: final String tKeyboardLine = tKeyboard.readLine(); 0219: if (tKeyboardLine.equals("")) 0220: { 0221: break; 0222: } 0223: final Person tTargetPerson = new Person(tKeyboardLine); 0224: System.out.print(tTargetPerson); 0225: final int tPosition = tList.indexOf(tTargetPerson); 0226: if (tPosition>=0) 0227: { 0228: System.out.println(" is at position " + tPosition); 0229: } 0230: else 0231: { 0232: System.out.println(" is absent"); 0233: } 0234: } 0235: } 0236: }
The program begins by obtaining the name of a file from the command line. It then reads lines from this file, each line containing the details about one person. As it reads each line, it creates a Person object and adds this object to a list. Having read the file, the program uses an Iterator to output the contents of the list. Finally, the program keeps reading lines from the keyboard (each line containing the details of a person) and finding out whether the person is in the list. It keeps doing this until the user of the program types in an empty line.