2016-03-11 25 views
-5

我已經嘗試了下面的方法,但仍然不斷收到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); 
    } 
    } 
} 
+0

花點時間通過[編輯求助]閱讀(HTTP://計算器。 com/editing-help)在幫助中心。堆棧溢出的格式與其他站點不同。您的帖子看起來越好,用戶就越容易幫助您。 – gunr2171

+0

你應該真的瞭解更多關於泛型的知識,而不是試圖用這個'instanceof'東西來實現它。和比較器。這只是讓它比必要更難!至少,首先讓它對String或Integer起作用。 –

回答

0

的主要問題是這些行:

int val = t.compare(arr[j - 1], arr[j]); 
System.out.println(val); 
if (val > 1) t.swap(arr[j - 1], arr[j]); 

由於您的compareswap方法採取實際數組的索引,這些應該是:

int val = t.compare(j - 1, j); 
System.out.println(val); 
if (val > 0) t.swap(j - 1, j); 

否則,您使用的數組元素作爲數組索引和數組中的值大於數組中元素的數量。

注意,在最後一行的條件太的變化:中val您返回這是唯一的價值> 1是4,而只發生比StringInteger其他類型。


在你swap方法,第一行:

o[i] = temp; 

應該是:

temp = o[i]; 
+0

是的,你是對的關於數組索引。謝謝 – SKY

0

考慮

for(int j=1;j<arr.length-i;j++) 

對於i = 0,

int val= t.compare(arr[j-1],arr[j]); 

用完的界限。

+0

嗨,當傳遞數組到我的測試類的構造函數時,我首先使用了一個增強的循環來確保我的數組是否正確傳遞,但是我也得到相同的錯誤 – SKY

相關問題