0

I have a hashmap:

HashMap<String,QuoteBean> map = new HashMap<String,QuoteBean>();

The QuoteBean is a normal bean:

class QuoteBean{
    String symbol;
    BigDecimal price;
    BigDecimal quoteprice;
    //setter and getter methods
}

Then, I get the values of the map which a collection of QuoteBean objects

Collection obs  =map.values(); //getting all the quoteobjects
List list = new ArrayList(obs); //converted to list

Then to sort:

Collection.sort(list, new SymbolComparator());

SymolComparator is:

public class SymbolComparator implements Comparator<QuoteBean>{
    String symbol;
    @Override
    public int compare(QuoteBean o1, QuoteBean o2) {
        String symbol1=o1.getProductId().getSymbol();
        String symbol2=o2.getProductId().getSymbol();
        return symbol1.compareTo(symbol2);
    }    
}

When I execute the code I get an exeception which says cannot convert String to QuoteBean and the exception throws on the first line.

3
  • Could you include the stacktrace? Commented Sep 27, 2010 at 23:37
  • Something tells me this isn't actually the code that's causing the error. Commented Sep 27, 2010 at 23:40
  • In the compare() method, you do o1.getProductId()... what does getProductId() return? Commented Sep 27, 2010 at 23:42

3 Answers 3

2

Are you positive you're not creating a list from the keys?

Collection obs  =map.values(); //getting all the quoteobjects
List list = new ArrayList(obs);

Just for fun make sure you can do

List<QuoteBean> beans = new ArrayList<QuoteBean>(map.values());
Sign up to request clarification or add additional context in comments.

2 Comments

I am pretty sure i am getting the values only from the map because once i get the list i am iterating through the list and printing the content which prints all the values...
Give us the stack trace, and start putting some debugging statements in your comparator function and we'll be able to help a lot more.
2

I think the mistake is with these two statements...

String symbol1=o1.getProductId().getSymbol();
String symbol2=o2.getProductId().getSymbol();

if you want to sort the based on string you could just say o1.symbol to get the string. I still don;t understand what getproductid() is used for.

Comments

0

I think instead of

o1.getProductId().getSymbol();

you should do

o1.getSymbol();

since the QuoteBean has the symbol as a property.

class QuoteBean{
    String symbol;
    BigDecimal price;
    BigDecimal quoteprice;
    //setter and getter methods
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.