Ho aggiunto alcuni oggetti semplici a un TreeSet, ma quando chiamo i metodi remove() e contains() di TreeSet, non funzionano. Tuttavia, quando eseguo un'iterazione sull'insieme, l'oggetto viene stampato. Gli oggetti dei dipendenti devono essere aggiunti all'insieme mentre l'unicità degli oggetti si basa sulla proprietà del nome dell'oggetto. La proprietà Id è il valore che deve essere ordinato, ma che non è univoco.Java TreeSet: remove e contains() non funziona
public class Employee {
private String name;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Two objects are considered equal if their names are equal
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (o.getClass() == this.getClass()) {
Employee p = (Employee) o;
if (p.getName() != null && this.getName() != null)
return this.getName().equals(p.getName());
else
return false;
} else {
return false;
}
}
}
//*******************************************************
public class EmployeeComp implements Comparator<Employee> {
// Sort Ids, but allow duplicates, hence this function is never returning 0
@Override
public int compare(Employee p1, Employee p2) {
int re = 0;
boolean scoreLt = (p1.getId() > p2.getId());
boolean scoreGt = (p1.getId() < p2.getId());
if(scoreLt)
re = -1;
if(scoreGt)
re = 1;
else
re = -1;
return re;
}
}
//*******************************************************
// Collection shall store unique names with ordered values like:
// Alex, 923
// Toni, 728
// Eddi, 232
// Peter, 232
// Eddi, 156 *** not allowed
import java.util.TreeSet;
public class Main {
private static EmployeeComp comp = new EmployeeComp();
private static TreeSet<Employee> employees = new TreeSet<Employee>(comp);
public static void main(String[] args) {
Employee p1 = new Employee();
p1.setName("Eddi");
p1.setId(232);
Employee p2 = new Employee();
p2.setName("Toni");
p2.setId(728);
Employee p3 = new Employee();
p3.setName("Peter");
p3.setId(232);
Employee p4 = new Employee();
p4.setName("Alex");
p4.setId(923);
employees.add(p1);
employees.add(p2);
employees.add(p3);
employees.add(p4);
// Here, contains() and remove() should check the object address
// and not perform their actions based on compareTo
}
}
No, ho fatto prima, ma ha commentato che in un secondo momento, quindi questo non può essere il reaosn. – user1812379
@fge certo, hai ragione, ho trascurato questo. –
OK, vedere la soluzione, e una cosa che dovete tenere a mente: non si può fare ciò che si vuole sia con '.equals()' /'.hashCode() 'o da soli un' Comparator' - non si può avere la vostra sia torta e mangiarlo. Il mio esempio "BigDecimal" avrebbe già dovuto darti un suggerimento! – fge