Interview Question

Software Technical Lead (Java) Interview Saint Louis, MO

Write an AscendingSortedLongList and

  DescendingSortedLongList class ... and write some JUnit classes associated with them ...
Tags:
java
Answer

Interview Answer

1 Answer

0

package sortedlist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Highly inefficient implementation of a sorted long list.
 */
public class AscendingSortedLongList implements SortedLongList {
    protected ArrayList<Long> list;

    public AscendingSortedLongList() {
        this(new ArrayList<Long>());
    }

    public AscendingSortedLongList(List<Long> initialList) {
        this.list = new ArrayList<Long>(initialList);
        sort();
    }

    protected void sort() {
        Collections.sort(this.list);
    }

    public void add(Long item) {
        this.list.add(item);
        sort();
    }

    public int getPositionOf(Long item) {
        return this.list.indexOf(item);
    }

    public Long get(int position) {
        try {
            return this.list.get(position);
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    }

    public int length() {
        return this.list.size();
    }

    public void printSortedContents() {
        System.out.print(">");
        boolean comma = false;
        for (Long longValue : this.list) {
            if (comma) {
                System.out.print("," + longValue);
            } else {
                System.out.print(longValue);
                comma = true;
            }
        }
        System.out.println();
    }

    public SortedLongList reverseSort() {
        return new DescendingSortedLongList(this.list);
    }
}

Interview Candidate on Feb 20, 2012

Add Answers or Comments

To comment on this, Sign In or Sign Up.