I wrote this method. I don’t understand why it is write out this exception:
Exception in thread “main” java.lang.ClassCastException: Kocsma.Sör cannot be cast to java.lang.Comparable
Anybody know what is my mistake?
The compiler reference this line
beers.put(beer, dl);
This is my code:
private Map<Beer, Integer> beers = new TreeMap<Beer, Integer>();
public void Upload(Beer beer, int dl) {
int d = 0;
Beer s = null;
for (Map.Entry<Beer, Integer> item : beers.entrySet()) {
if (item.getKey().equals(beer)) {
d = item.getValue();
s = item.getKey();
}
}
if (s != null) {
beers.put(s, d + dl);
}else
beers.put(beer, dl); // Here is the problem by the Compiler
}
Class Kocsma:
public Kocsma() {
Upload(new Beer("Borsodi sör", 160, 4.6), 1000);
Upload(new Beer("Pilsner Urquell", 250, 4.4), 800);
Upload(new Beer("Soproni Ászok", 150, 4.5), 900);
Upload(new Beer("Dreher Classic", 200, 5.2), 600);
}
Your
Beerclass needs to implementComparable<Beer>or you need to provide aComparator<Beer>to theTreeMapconstructor.TreeMapstores keys by using a binary search tree. This works without effort for some common classes likeIntegerandStringbecause they are naturally sortable and implementComparableout of the box. However, for yourBeerclass, you would have to implement it manually.If
Beeris not a good candidate for comparisons (most things aren’t) then consider usingHashMapinstead, and overridingequals()andhashCode()onBeer(see Effective Java Chapter 3 for a great reference on this).