この質問はちょっと長いので、ご容赦ください。
配列をソートするために構築された私の本で説明されている SelectionSort メソッドを変換し、double または int を入力して機能させることができるように汎用にする必要があります。
ジェネリック配列は許可されていないようなので、ArrayList を使用しようとしています。ここでの問題は、int と double が Integer と Double のラッパーに含まれるようになったため、SelectionSort メソッドが壊れてしまうことです。
私はそれを修正しようとしましたが、運がありません。元の SelectionSort メソッドを以下に投稿し、次に作成中のクラスとドライバーを投稿します。
元の選択ソート:
public class SelectionSort {
private int[] data;
private static final Random generator = new Random();
public SelectionSort(int size) {
data = new int[size];
for(int i = 0; i < size; i++) {
data[i] = 10 + generator.nextInt(90);
}
}
public void sort() {
int smallest;
for(int i = 0; i < data.length - 1; i++) {
smallest = i;
for(int index = i + 1; index < data.length; index++) {
if(data[index] < data[smallest]) {
smallest = index;
}
}
swap(i, smallest);
}
}
public void swap(int first, int second) {
int temporary = data[first];
data[first] = data[second];
data[second] = temporary;
}
}
私の単純なドライバープログラム:
public class GenericsDriver {
public static void main(String[] args) {
SelectionSort<Integer> intSort = new SelectionSort<Integer>();
intSort.AddGrade(100);
intSort.AddGrade(90);
intSort.AddGrade(50);
intSort.AddGrade(80);
intSort.AddGrade(95);
intSort.PrintNumbers();
//sort here
intSort.PrintNumbers();
SelectionSort<Double> doubleSort = new SelectionSort<Double>();
doubleSort.AddGrade(100.1);
doubleSort.AddGrade(90.4);
doubleSort.AddGrade(50.7);
doubleSort.AddGrade(100.2);
doubleSort.AddGrade(100.5);
doubleSort.PrintNumbers();
//sort here
doubleSort.PrintNumbers();
}
}
新しいクラスと SelectionSort メソッドを再利用しようとする私の試み:
import java.util.*;
public class SelectionSort <T> {
private Array<T> numbers;
public SelectionSort() {
numbers = new ArrayList<T>();
}
public void AddGrade(T number) {
numbers.add(number);
}
public void PrintNumbers() {
System.out.println(numbers.toString());
}
public <T extends Comparable<T>> selectionSort() {
int smallest;
for(int i = 0; i < numbers.size(); i++) {
smallest = i;
for(int index = i + 1; index < numbers.size(); index++) {
if(numbers.) {
//I've tried everything here...
//from using number.get(index), and everything else
//I could think of
}
}
}
}
public void swap(int first, int second) {
}
}
ご覧のとおり...新しいクラス内で並べ替えや交換を行うことができませんでした。私はそれを働かせることができません。私の指示には、ソート方法で > を使用する必要があるというヒントがあります...しかし、.compareTo() メソッドを使用する機能は何もありません。
これは私の本からの実際の指令です: 図 19.6 と 19.7 の sort プログラムに基づいてジェネリック メソッド selectionSort を書きます (これが上で示したコードです)。Integer 配列と Float 配列を入力、並べ替え、出力するテスト プログラムを作成します。ヒント: メソッド selectionSort の型パラメータ セクションで > を使用すると、メソッド compareTo() を使用して、T が表す型のオブジェクトを比較できます。
誰かがここで私にいくつかのガイダンスを教えてもらえますか? ありがとう。