Java 我正在尝试使用定制的比较方法实现buublesort,但我总是不断获取ArrayIndexOutofBond异常
我已经尝试了下面的方法,但仍然不断获得arrayindexoutofbound异常Java 我正在尝试使用定制的比较方法实现buublesort,但我总是不断获取ArrayIndexOutofBond异常,java,object,Java,Object,我已经尝试了下面的方法,但仍然不断获得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) {
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;
}
}
我在其中实现上述bubblesort比较的类:-
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);
}
}
}
考虑
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]);
由于比较和交换方法实际上采用数组索引,因此应该是:
int val = t.compare(j - 1, j);
System.out.println(val);
if (val > 0) t.swap(j - 1, j);
temp = o[i];
否则,将使用数组元素作为数组索引,并且数组中的值大于数组中的元素数
请注意最后一行的条件也发生了变化:返回的val的唯一值>1是4,并且仅对String和Integer以外的类型发生
在交换方法中,第一行:
o[i] = temp;
应该是:
int val = t.compare(j - 1, j);
System.out.println(val);
if (val > 0) t.swap(j - 1, j);
temp = o[i];
花点时间阅读帮助中心中的。堆栈溢出上的格式设置与其他站点不同。你的文章看起来越好,用户就越容易帮助你。你应该真正了解更多关于泛型的知识,而不是试图用这个实例来实现它。和比较器。这只会让事情变得更难!至少,首先让它为String或Integer工作。嗨,在将数组传递给我的测试类的构造函数时,我首先使用了一个增强的for looop来确保我的数组是否被正确传递,但我也得到了相同的错误是的,关于数组索引,你是对的。非常感谢。