在更新了产品的一些信息后,我试图更改打印菜单中产品的位置。具体而言,按降序排列“数量”。如果产品数量相同,则列表将按升序"UnitPrice“字段排序。
最初,如果我再添加一个产品,compareTo()函数可以正常工作,但是在使用了产品更新函数之后,compareTo()函数就不能工作了。我在这个项目中使用TreeSet。有人能给我解释一下这个案子吗?非常感谢。
这是我的compareTo()函数
@Override
public int compareTo(Product o) {
if (this.getQuantity() < o.getQuantity()) {
return 1;
}
if (this.getQuantity() == o.getQuantity()) {
return this.unitPrice-o.unitPrice;
}
return -1;
}
这是我的更新函数
public void updateInfo() {
Scanner sc = new Scanner(System.in);
String id, productName, quantity, unitPrice, numberForAvail;
while (true) {
try {
System.out.print("Input products's id: ");
id = sc.nextLine().toUpperCase();
if (id.isEmpty()) {
this.id = this.id;
} else {
if (!id.matches(letter_regEx) || id.length() < 5) {
throw new Exception();
}
this.id = id;
}
break;
} catch (Exception e) {
System.out.println("ID must be character and lenght > 5");
}
}
while (true) {
try {
System.out.print("Input prodct's name: ");
productName = sc.nextLine().toUpperCase();
if (productName.isEmpty()) {
this.productName = this.productName;
} else {
if (!productName.matches(letter_regEx)) {
throw new Exception();
}
this.productName = productName;
}
break;
} catch (Exception e) {
System.out.println("Invalid name");
}
}
while (true) {
try {
System.out.print("Input Unit Price: ");
unitPrice = sc.nextLine();
if (unitPrice.isEmpty()) {
this.unitPrice = this.unitPrice;
} else {
if (!unitPrice.matches("^([1-9][0-9]{0,3}|10000)$")) {
throw new Exception();
}
this.unitPrice = Integer.parseInt(unitPrice);
}
break;
} catch (Exception e) {
System.out.println("Unit price must be > 0 and < 10000");
}
}
while (true) {
try {
System.out.print("Input quantity: ");
quantity = sc.nextLine();
if (quantity.isEmpty()) {
this.quantity = this.quantity;
} else {
if (!quantity.matches("^([1-9][0-9]{0,2}|1000)$")) {
throw new Exception();
}
this.quantity = Integer.parseInt(quantity);
}
break;
} catch (Exception e) {
System.out.println("Quantity must be > 0 and < 1000");
}
}
while (true) {
try {
System.out.print("Input status [0(not available)/ 1 (available)]: ");
numberForAvail = sc.nextLine();
if (numberForAvail.isEmpty()) {
this.numberForAvail = this.numberForAvail;
} else {
if (!numberForAvail.matches("^[01]$")) {
throw new Exception();
}
this.numberForAvail = Integer.parseInt(numberForAvail);
break;
}
} catch (Exception e) {
System.out.println("Status must 0 for NOT AVAILABLE and 1 for AVAILABLE");
}
}
if (this.numberForAvail == 0) {
status = "Not available";
} else {
status = "Available";
}
}
这是我的输出
当我添加一个产品时:
当我把NGUYEN的数量改为125的时候,它不起作用了
发布于 2022-09-10 09:44:17
元素根据插入时与元素的比较方式添加到集合中的位置。如果您更改一个元素,使其顺序发生变化,那么像TreeSet
这样的数据结构的所有不变量都会被破坏,任何事情都可能发生。在将元素插入依赖于它们的数据结构后,您永远不应该更改元素的这些属性。这意味着,在使用基于顺序的数据结构(如TreeSet
)时,不应该更改更改顺序的字段,而在使用基于哈希的结构(如HashSet
)时,不应该更改更改哈希代码的字段。
如果确实需要修改值,则需要从TreeSet
中删除它,然后对其进行变异,然后将其与新的顺序放在一起。或者,更好的是,拥有一个不可变的类,只需创建一个新实例来替换它。默认情况下,类是不可变的,这首先避免了所有这些杂乱无章的事情。
https://stackoverflow.com/questions/73673834
复制相似问题