У меня есть такой вот TreeMap < Class, String> и мне нужно вывести значение по ключу, если оно имеется. В findKey() пытаюсь реализовать это, но функция показывает, что такого ключа нет, хотя на деле он есть. Подскажите, как решить эту проблему?
public class MyCompu {
TreeMap<CharMusic, String> tm = new TreeMap<CharMusic, String>(new MyNameComp());
public TreeMap<CharMusic, String> base() {
this.tm.put(new CharMusic(2018, "Alisa -- Holder"), "pop");
this.tm.put(new CharMusic(2015, "Hola -- Dreams"), "rock");
return tm;
}
public void findKey() {
CharMusic charMusic1 = new CharMusic(2018, "Alisa -- Holder");
for (Map.Entry product : base().entrySet()) {
if (tm.containsKey(charMusic1)) {
System.out.println(product.getKey());
}
}
}
public static void main(String a[]) throws FileNotFoundException {
MyCompu myTMCompUserDefine = new MyCompu();
myTMCompUserDefine.printKey();
}
}
class MyNameComp implements Comparator<CharMusic> {
@Override
public int compare(CharMusic e1, CharMusic e2) {
if (e1.getYear() > e2.getYear()) {
return 1;
} else {
return -1;
}
}
}
class CharMusic {
private String tittle;
private int year;
public CharMusic(int s, String n) {
this.tittle = n;
this.year = s;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (tittle == null ? 0 : tittle.hashCode());
result = prime * result + year;
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
CharMusic other = (CharMusic) o;
if (year != other.year)
return false;
return o instanceof CharMusic &&
((CharMusic) o).tittle.equals(tittle);
}
}
if (tittle != other.tittle)
строки сравнивайте через equals