【问题标题】:Creating a 'sort' method for array objects in a linked list为链表中的数组对象创建“排序”方法
【发布时间】:2014-03-29 05:10:57
【问题描述】:

我有一个项目需要我们创建一个对象数组,然后我们将它放在一个链表中,我有点卡住了,因为我在编写/实现我的排序方法时遇到了麻烦,该排序方法应该对链表进行排序。这是我已经走了多远的代码。顺便说一句,对象名称是“温度”;谢谢你。

public class SelectionSort
{
   private static void SelectionSort (Temperature[] array, int size)
   { 
      for ( int i = 0; i < size - 1; i++ )
      { 
         int indexLowest = i; 
         for ( int j = i + 1; j < size; j++ )
         {
            if ( array[j] < array[indexLowest] ) 
               indexLowest = j;

            if ( array[indexLowest] != array[i] )
            { 
               Temperature temp = array[indexLowest];
               array[indexLowest] = array[i]; 
               array[i] = temp; 
            }// if
         }//for j
      }// for i 
   }// method 
}

【问题讨论】:

  • 我相信温度是你自己的课。你能把它贴出来吗?你想在什么地方分类。还要检查这个 - mkyong.com/java/…
  • “有问题”在哪方面?说明您获得的结果以及它们与预期结果有何不同。
  • 这不是 C++。如果是,请查看std::sort

标签: java arrays sorting object linked-list


【解决方案1】:

我认为,你的问题是线

if ( array[j] < array[indexLowest] )

根据您的方法签名,array[j]array[indexLowest] 都属于温度类型。因此它们不是原始类型,因此无法与&lt; 进行比较。这显然会导致编译器错误,您真的应该告诉我们。

要像这样比较对象,您有两种可能性:

1) 让Temperature 类实现Comparable&lt;Temperature&gt;。此接口将强制您将方法public int compareTo(Temperatue other) 添加到您的类Temperature。通过以下方式实现:

@Override
public int compareTo(Temperatue other) {
     if (/* this is smaller than other */) {
        return -1;
    } else if (/* this is greater than other */) {
        return 1;
    } else {
        return 0;
    }
}

您可以根据需要返回任何其他正整数或负整数。根据Temperature中的字段自行实现比较。

在有问题的行中使用:

if ( array[j].compareTo(array[indexLowest]) < 0 )

2) 为您的温度类编写一个比较器。

public class TemperatureComparator implements Comparator<Temperature> {
    public int compare(Temperature t1, Temperature t2) {
        if (/* t1 is smaller than t2 */) {
            return -1;
        } else if (/* t1 is greater than t2 */) {
            return 1;
        } else {
            return 0;
        }
    }
}

逻辑类似。现在你可以在你的排序方法中使用这个比较器了

private static void SelectionSort (Temperature[] array, int size) {
    Comparator<Temperature> comparator = new TemperatureComparator();
    ...
        if ( comparator.compare(array[j], array[indexLowest]) < 0 )
    ...
}

【讨论】:

    猜你喜欢
    • 2015-06-08
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 2019-09-07
    • 2018-04-27
    相关资源
    最近更新 更多