気温と日の Arraylist があります。そして、挿入ソート方法を使用して配列リストをソートしました。Collections.sort(dailytemps) 行をコメントアウトしたためでしょうか? エラーだったのでコメントアウトしました
これが私のコードです:
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class DailyTemperature
{
//variables
private double temperature;
private String day;
//getTemp & setTemp methods
public double getTemp()
{
return temperature;
}
public void setTemp(double newTemp)
{
temperature = newTemp;
}
//getDay & setDay methods
public String getDay()
{
return day;
}
public void setDay(String newDay)
{
day = newDay;
}
//constructor
public DailyTemperature(String day, double temperature)
{
this.day = day;
this.temperature = temperature;
}
//compareTo method used for Comparable interface
public int compareTo(DailyTemperature other)
{
if (temperature < other.temperature) return -1;
if (temperature == other.temperature) return 0;
return -1;
}
//toString method to print out original arraylist contents and sorted arraylist contentes
public String toString()
{
return("Day of Week: " + this.getDay() +
" - Temperature: " + this.getTemp());
}
}
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class DailyTemperatureList
{
public static void main (String [] args)
{
ArrayList<DailyTemperature> dailytemps = new ArrayList<DailyTemperature>();
dailytemps.add(new DailyTemperature("Mon", 87.1));
dailytemps.add(new DailyTemperature("Tue", 88.3));
dailytemps.add(new DailyTemperature("Wed", 81.2));
dailytemps.add(new DailyTemperature("Thu", 84.0));
dailytemps.add(new DailyTemperature("Fri", 76.3));
//original list printout
System.out.println("Original List:" );
System.out.println( dailytemps.toString() );
System.out.println(" "); //empty line
//method to sort array list
insertionSort(dailytemps);
//sorted list printout
System.out.println("Sorted List:" );
System.out.println( dailytemps.toString() );
//Collections.sort(dailytemps);
}
static void insertionSort(ArrayList<DailyTemperature> dailytemps)
{
DailyTemperature temp = null;
int position = 0;
//loop from 2nd element on
for (int i = 1; i < dailytemps.size(); i++)
{
temp = dailytemps.get(i);
position = i;
while ( 0 < position && temp.compareTo(dailytemps.get(position - 1)) < 0)
{
dailytemps.set(position, dailytemps.get(position - 1));
position--;
}
dailytemps.set(position,temp);
}
}
}