我填写了您的代码中缺少的部分。您应该阅读How do I ask a good question 以及指向How to create a Minimal, Reproducible Example 的链接。
下面的代码是GroceryItem 类,它只包含一个成员,即name,它是杂货商品的名称。由于您的问题仅涉及操纵此成员,因此我没有尝试猜测该类还需要哪些其他数据。
代码后的解释。
import java.util.ArrayList;
import java.util.List;
public class GroceryItem implements Comparable<GroceryItem> {
private String name;
public GroceryItem(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override // java.lang.Comparable
public int compareTo(GroceryItem other) {
if (other == null) {
return 1;
}
else {
String otherName = other.getName();
if (name == null) {
if (otherName == null) {
return 0;
}
else {
return -1;
}
}
else {
if (otherName == null) {
return 1;
}
else {
return name.compareTo(otherName);
}
}
}
}
@Override // java.lang.Object
public boolean equals(Object other) {
boolean equal = false;
if (other instanceof GroceryItem) {
GroceryItem otherItem = (GroceryItem) other;
if (name == null) {
equal = otherItem.getName() == null;
}
else {
equal = name.equals(otherItem.getName());
}
}
return equal;
}
@Override // java.lang.Object
public int hashCode() {
return name == null ? 0 : name.hashCode();
}
@Override // java.lang.Object
public String toString() {
return name;
}
public static void main(String[] args) {
List<GroceryItem> inventory = new ArrayList<>();
inventory.add(new GroceryItem("apple"));
inventory.add(new GroceryItem("pear"));
inventory.add(new GroceryItem("banana"));
inventory.add(new GroceryItem("orange"));
inventory.add(new GroceryItem("beetroot"));
inventory.add(new GroceryItem("onion"));
inventory.add(new GroceryItem("lettuce"));
inventory.add(new GroceryItem("carrot"));
inventory.add(new GroceryItem("guava"));
inventory.add(new GroceryItem("lychee"));
inventory.add(new GroceryItem("kiwi"));
int n = inventory.size();
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (inventory.get(j).compareTo(inventory.get(j+1)) > 0) {
// swap inventory[j+1] and inventory[j]
GroceryItem temp = inventory.get(j);
inventory.set(j, inventory.get(j+1));
inventory.set(j+1, temp);
}
}
}
System.out.println();
}
}
上面的代码创建了一个包含十一个元素的GroceryItem 对象的List。填充List 后,冒泡排序 在两个嵌套的for 循环中执行。最后打印出排序后的List。
请注意,GroceryItem 类还实现了方法toString(),以便在打印GroceryItem 的实例时使输出可读。
如果将来您需要使用GroceryItem 作为java.util.HashMap 的键,那么GroceryItem 将需要覆盖方法hashCode(),如果一个类覆盖方法hashCode(),那么它也应该覆盖方法equals()。因此,这就是为什么上面的代码包含那些被覆盖的方法。请注意,这些方法(equals()、hashCode() 和 toString())都不是冒泡排序所必需的。
运行上述代码时的输出为:
[apple, banana, beetroot, carrot, guava, kiwi, lettuce, lychee, onion, orange, pear]