我试过下面的代码我得到数组索引超出绑定的异常。任何人都可以帮助我。
public class RevSortedArry {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr1[]={45,63,82,13,5,907,342,654,-776,-123};
Arrays.sort(arr1);
System.out.print("Sorted Array is :: ");
for(int i=0; i<arr1.length; i++)
{
if(i != 0){
System.out.print(", ");
}
System.out.print(arr1[i]);
}
int arr2[]=new int[arr1.length];
System.arraycopy(arr1,0,arr2,0,arr1.length);
ArrayList arrayList = new ArrayList(Arrays.asList(arr2));
Collections.reverse(arrayList);
System.out.println(arrayList);
}
}
答案 0 :(得分:0)
也许再次检查您的代码,我已编译并在代码下面运行,没有任何问题,
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr1[]={45,63,82,13,5,907,342,654,-776,-123};
Arrays.sort(arr1);
System.out.print("Sorted Array is :: ");
for(int i=0; i<arr1.length; i++)
{
if(i != 0){
System.out.print(", ");
}
System.out.print(arr1[i]);
}
int arr2[]=new int[arr1.length];
System.arraycopy(arr1,0,arr2,0,arr1.length);
ArrayList arrayList = new ArrayList(Arrays.asList(arr2));
Collections.reverse(arrayList);
System.out.println(arrayList);
}
}
答案 1 :(得分:0)
试试这个 - 查看第二个for循环及其条件:
public class Sort
{
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr1[]={45,63,82,13,5,907,342,654,-776,-123};
Arrays.sort(arr1);
System.out.print("Sorted Array is : ");
for(int i=0; i<arr1.length; i++)
{
if(i != 0){
System.out.print(", ");
}
System.out.print(arr1[i]);
}
System.out.println();
int arr2[]=new int[arr1.length];
System.arraycopy(arr1,0,arr2,0,arr1.length);
ArrayList<Integer> arr2List = new ArrayList<>();
System.out.print("Reverse: ");
for (int i = arr2.length-1; i >=0; i--) {
//adding into list
arr2List.add(arr2[i]);
//printvalue
System.out.print(arr2[i]+" ");
}
}
}`
答案 2 :(得分:0)
试试这个:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class RevSortedArry {
public static void main(String[] args) {
int arr1[]={45,63,82,13,5,907,342,654,-776,-123};
System.out.println("Before Sorting : " + Arrays.toString(arr1));
Arrays.sort(arr1);
System.out.print("Sorted Array is :: " );
for(int i=0; i<(arr1.length); i++)
{
System.out.print((arr1[i]) + "\t");
}
int arr2[]=new int[arr1.length];
//Copying arr1 into arr2
System.arraycopy(arr1,0,arr2,0,arr1.length);
//newArray for storing arr2 as Integer
Integer[] newArray = new Integer[arr2.length];
int i = 0;
for (int value : arr2) {
newArray[i++] = Integer.valueOf(value);
}
//creating arrayList of type integer
ArrayList<Integer> arrayList =
new ArrayList<Integer>(Arrays.asList(newArray));
System.out.println("\nArray List is :" + arrayList);
Collections.reverse(arrayList);
System.out.println(arrayList);
}
}
更改是我已将int数组arr2转换为整数数组newArray可能会导致您出现问题,但我的代码也没有任何异常。请试一试。