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.

for(int i = 0; i < items.length(); i++){
if (!items.isEmpty()) {
if (items.isEmpty()){
 else {
      Object tmp = items.getFirst();
      count = 0;
      while (items.hasNext()){
           if (o.number > items.getNthObject(count).number){
                 items.insertAt(count, o);
 for (int i = 0; i < items.length(); i++) {

Leave a Reply

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

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

Facebook photo

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

Connecting to %s