views:

107

answers:

2

I am trying to sort my ArrayList, but when I check the first item in my supposedly sorted array, it is incorrect. I am not sure why? Am I missing anything?

Here is my Comparator:

package org.stocktwits.helper;

import java.util.Comparator;

import org.stocktwits.model.Quote;

public class NameComparator implements Comparator<Quote>
{

    public int compare(Quote o1, Quote o2) {
        return o1.getName().compareToIgnoreCase( o2.getName());
    }
}

Here is how I perform the actual sort:

Collections.sort(quotes, new NameComparator());

Here is my test data

quotes = ["Yahoo", "Microsoft", "Apple"]

After sorting I want it to be:

quotes = ["Apple", "Microsoft", "Yahoo"]`

However when I pull out the first item after the sort, I get: "Yahoo"

+1  A: 

Your code works. It must be somewhere else.
Code on ideone

Colin Hebert
Any reason for the downvote ?
Colin Hebert
+1 to compensate downvote
Willi
A: 

Similar version works for me fine:

        class NameComparator implements Comparator<String>
    {

        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase( o2 );
        }
    }

    ArrayList<String> s = new ArrayList<String>(3);
    s.add("Yahoo");
    s.add("Microsoft");
    s.add("Apple");

    Collections.sort(s, new NameComparator());
    System.out.println(s);

Could you take here code, when you fill and read from collection?

Jan Wegner