Collections / List object question

Each object in a collection called items has two variables, a String name and an int number. The collection is ordered in ascending order of number.

The collection supports the following methods:

  • isEmpty()
  • getFirst()
  • getNext()
  • getNthObject(int n)
  • hasNext()
  • length()
  • insertAtStart(Obj o)
  • insertAtEnd(Obj o)
  • insertAtN(int n, Obj o)
  1. Write an algorithm using a for loop that prints the names of each object (4 marks)
  2. Write an algorithm using a while loop that prints the names of each object (4 marks)
  3. Write an algorithm that inserts an object o at the correct place in the list (6 marks)
  4. Write an algorithm to sort the collection in descending order (2 marks)

My Answers below. These aren’t the only right answers. There are lots of different ways you can code these.

(a)
for(int i = 0; i < items.length(); i++){
      System.out.println(items.getNthObject(i).name);
 }
(b)
if (!items.isEmpty()) {
      System.out.println(items.getFirst().name);
      while(items.hasNext()){
           System.out.println(items.getNext().name);
      }
 }
(c)
if (items.isEmpty()){
      items.insertAtStart(o);
 }
 else {
      Object tmp = items.getFirst();
      count = 0;
      while (items.hasNext()){
            count++;
           if (o.number > items.getNthObject(count).number){
                 items.insertAt(count, o);
            }    
 }
(d)
 for (int i = 0; i < items.length(); i++) {
      items.insertAtStart(items.getNthObject(i));
 }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s