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.getProductI开发者_StackOverflow中文版d().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.
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());
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.
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
}
精彩评论