Sheehan Alam
Sheehan Alam

Reputation: 60919

Sorting ArrayList Not Working Properly

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"

Upvotes: 0

Views: 2062

Answers (2)

Jan Wegner
Jan Wegner

Reputation: 321

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?

Upvotes: 1

Colin Hebert
Colin Hebert

Reputation: 93197

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

Upvotes: 4

Related Questions