Tôi đã thêm một số đối tượng đơn giản vào TreeSet, nhưng khi tôi gọi phương thức remove() và contains() của TreeSet, chúng không hoạt động. Tuy nhiên, khi tôi lặp qua tập hợp, đối tượng được in. Các đối tượng nhân viên sẽ được thêm vào tập hợp trong khi tính duy nhất của đối tượng dựa trên thuộc tính tên đối tượng. Thuộc tính Id là giá trị cần được sắp xếp, nhưng không phải là duy nhất.Java TreeSet: xóa và chứa() không hoạt động
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
}
}
Không, tôi đã thực hiện điều đó trước tiên, nhưng đã nhận xét sau, vì vậy đây không thể là sự lặp lại. – user1812379
@fge chắc chắn, bạn nói đúng, tôi đã bỏ qua điều này. –
OK, xem giải pháp, và một điều bạn cần lưu ý: bạn không thể làm những gì bạn muốn với '.equals()' /'.hashCode() 'hoặc' Comparator' một mình - bạn không thể có cả hai bánh và ăn nó. Ví dụ 'BigDecimal' của tôi đã cho bạn một gợi ý! – fge