Source of ListsAreLists.java


  1: // ListsAreLists.java
  2: //  week09 code
  3: //  Isn't it annoying that we have to make TWO methods to print out lists --
  4: //  one for ArrayLists and one for LinkedLists?
  5: //  Well, it turns out that we don't!
  6: // See also SillyDuplication.java

  8: import java.util.Scanner;
  9: import java.util.ArrayList;
 10: import java.util.LinkedList;
 11: import java.util.List;

 13: public class ListsAreLists {

 15:     // this method prints a List, 8 elements per line
 16:     //  NOTE: the body is exactly the same as printArrayList
 17:     //        and printLinkedList from SillyDuplication.java
 18:     public static void printList(List<Integer> list) {
 19:         int perLine = 8;
 20:         int count = 0;
 21:         for (int num : list) {
 22:             if (count % perLine == 0) {
 23:                 System.out.println();
 24:             }
 25:             System.out.print("\t" + num);
 26:             count++;
 27:         }
 28:         System.out.println();
 29:     }

 31:     public static void main(String[] args) {
 32:         Scanner kbd = new Scanner(System.in);

 34:         ArrayList<Integer> aList = new ArrayList<Integer>();
 35:         LinkedList<Integer> lList = new LinkedList<Integer>();
 36:         for (int i = 1; i < 30; i++) {
 37:             aList.add(i * i + 7 * i - 12);
 38:             lList.add(i * i - 3 * i + 42);
 39:         }

 41:         System.out.println("\nHere is my ArrayList:");
 42:         printList(aList);
 43:         System.out.println("\nHere is my LinkedList:");
 44:         printList(lList);
 45:         System.out.print("\nPress Enter...");
 46:         kbd.nextLine();
 47:         System.out.println();

 49:         List<Integer> listA = new ArrayList<Integer>();
 50:         List<Integer> listL = new LinkedList<Integer>();
 51:         for (int i = 1; i < 30; i++) {
 52:             listA.add(i * i + 4 * i - 7);
 53:             listL.add(i * i - 9 * i + 42);
 54:         }

 56:         System.out.println("\nHere is my List that's an ArrayList:");
 57:         printList(listA);
 58:         System.out.println("\nHere is my List that's a LinkedList:");
 59:         printList(listL);
 60:         System.out.print("\nPress Enter...");
 61:         kbd.nextLine();
 62:         System.out.println();

 64:         // Lists must be ArrayLists or LinkedLists (or some other List class)
 65:         // List<Integer> nope = new List<Integer>();
 66:     }

 68: }