Dirty Code – An Update

You might remember my little hack to sort list elements by their values:

TreeMap<Double, Integer> tree = new TreeMap<>(Collections.reverseOrder());
for (int i = 0; i < customerNumber; i++) {
    tree.put(requirement(i) + Math.random(), i);
}
List<Integer> orderedCustomers = new ArrayList<>(tree.values());

After a lot of research, I finally found a more elegant solution. First of all, I’m using a PriorityQueue instead of a tree. PriorityQueues allow duplicates, which is preferrable in this case since values are not guaranteed to be unique. Secondly, implementing a custom Comparable ensures a clear and readable structure.

class Element implements Comparable<Element> {

    private final int key;
    private final int value;

    Element(int key, int value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public int compareTo(Element anotherElement) {
        return compare(getValue(), anotherElement.getValue());
    }

    private int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }

    public int getKey() {
        return key;
    }

    public int getValue() {
        return value;
    }
}

That’s it. This solution is still too complicated for my taste, but at least it’s easy to understand.

Advertisements

1 thought on “Dirty Code – An Update”

  1. I do agree with all the ideas you have offered in your post. Sono davvero e può sicuramente certo lavoro. Ancora Tuttavia, i posti sono troppo short per principianti . maggio prolungare li un po ‘ dal next tempo? Grazie per il post.

    Like

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s