java - 尝试按字母顺序对对象数组进行排序,但对象无法转换为字符串

标签 java arrays sorting object

我正在创建一个酒店程序,其中有一个填充对象(房间)的数组,每个房间都填充了一个客户名称。我使用交换排序按字母顺序对数组进行排序,但是我不断收到错误,指出 Room 无法转换为字符串。 我对 Java 相当陌生,我正在努力寻找解决方案。这是我下面的排序。我怎样才能克服这个问题?

private static void orderedView(Room hotelRef[]) {
    for (int i = 0; i < hotelRef.length; i++) {
        for (int j = i + 1; j < 12; j++) {

            if (hotelRef[i].compareTo(hotelRef[j]) > 0) {
                String temp;
                temp = hotelRef[i];
                hotelRef[i] = hotelRef[j];
                hotelRef[j]= temp;
            }
        }
    }
    System.out.print("Names in Sorted Order:");
    for (int i = 0; i < hotelRef.length - 1; i++) {
        System.out.println(hotelRef[i] + " ");

    }
    System.out.print(hotelRef[12 - 1]);

}

最佳答案

这里有一些问题:

  1. if (hotelRef[i].compareTo(hotelRef[j]) 如果 Room 实现 Comparable (或者您有一个自定义 Room.compareTo),实际上是按客户名称进行比较。如果没有,那么也许您需要:

    if(hotelRef[i].getCustomerName().compareTo(hotelRef[j].getCustomerName()) > 0)

  2. temp = hotelRef[i];:temp 是一个字符串变量,您正在尝试为其分配一个Room 。将 String temp; 更改为 Room temp;

如果您使用的是 Java-8 或更高版本,那么您可以使用 Arrays.sort 对其进行更简单的排序和 Comparator.comparing :

Arrays.sort(hotelRef, Comparator.comparing(Room::getCustomerName));
// or whatever the customer name's getter method is named

关于java - 尝试按字母顺序对对象数组进行排序,但对象无法转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49161080/

相关文章:

java - 无效的 hibernate 警告? '@Access(AccessType.PROPERTY) on a field has no effect'

java - 如何在运行时使用其他形状制作自定义圆形?

python - 按多维数组中的值(前 5 个)排序

arrays - 如何在批处理中返回数组的元素?

python - numpy中的插入排序?

java - 通过选择排序按字母顺序对字符串数组进行排序?

java - Maven 构建配置文件在子模块 pom 定义属性时执行

java - 通过Java在MySQL中插入文件文件路径

ruby-on-rails - “natural” 在 Ruby 中对数组进行排序

arrays - 如果满足特定条件,则删除数组行