Week 6 Notes and Questions

Abstract, Interface, Collections

  • Collections:

    Questions

    1. Using the "Person" class (that we looked at in week 4), write a program that does:
            // ** a ** 
            for (int i=0; i<20; i++) {
               // Create a new person with random age
               int age = (int) (Math.random() * 70);
               Person p = new Person("Person number " + i, age);
            }
            // ** b **
      
    2. How many "Person"s does this code create?
    3. Where are they by the time you get to line "b"?
    4. At line "a", create a "LinkedList" object called "myCollection". Inside the loop, add each new Person to myCollection.
    5. Where are all the Person objects now by the time you get to line "b"?
    6. At line "b", create a new Iterator to fetch each item out of myCollection and print them out. What order do they come out in?
    7. Modify the "Person" class so that the definition now reads:
          class Person implements Comparable { ...
      
      What happens when you try to compile it? What have you got to do to fix this?
    8. Fix "Person" so it now compiles as a "Comparable" class. Now change your program so that "myCollection" is a "TreeSet". What difference does that make to the results?
    9. Change the program so that instead of using a "TreeSet", you use a "Stack". What difference does that make to the results?
    10. What is the problem with using "TreeSet" for this program? How would you fix this?
    11. Implement the fix described in the previous answer

    Back to index page