我已經嘗試了下面的方法,但仍然不斷收到arrayindexoutofbound異常。我想實現一個使用自定義比較方法buublesort,但我總是得到ArrayIndexOutOfBound異常
public class Test {
private Object[] o;
String type, s[];
Integer[] i = new Integer[50];
Object temp = null;
public <T> Test(T[] obs) {
this.o = obs;
if (obs[1] instanceof String) {
type = "string";
} else if (obs[1] instanceof Integer) {
type = "integer";
}
if (type == "string") s = (String[]) o;
else if (type == "integer") i = (Integer[]) o;
// System.out.println(type);
}
public int compare(int one, int two) {
if (type == "string") {
int l = s[one].compareTo(s[two]);
if (l == 0) return 0;
else if (l > 0) return 1;
else return -1;
} else if (type == "integer") {
System.out.println("integer");
for (int a : i) System.out.println(a);
if (i[one] > i[two]) return 1;
else if (i[one] < i[two]) return -1;
else return 0;
}
return 4;
}
public void swap(int i, int j) {
o[i] = temp;
o[i] = o[j];
o[j] = temp;
}
}
我在哪裏實施上述的類比較的冒泡: -
import jsoup.Test;
public class BubbleInt {
public static void main(String args[]) {
Integer[] arr = {2, 1, 8, 7};
Test t = new Test(arr);
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 1; j < arr.length - i; j++) {
int val = t.compare(arr[j - 1], arr[j]);
System.out.println(val);
if (val > 1) t.swap(arr[j - 1], arr[j]);
}
}
for (int i : arr) {
System.out.println(i);
}
}
}
花點時間通過[編輯求助]閱讀(HTTP://計算器。 com/editing-help)在幫助中心。堆棧溢出的格式與其他站點不同。您的帖子看起來越好,用戶就越容易幫助您。 – gunr2171
你應該真的瞭解更多關於泛型的知識,而不是試圖用這個'instanceof'東西來實現它。和比較器。這只是讓它比必要更難!至少,首先讓它對String或Integer起作用。 –