java - 使用arraylist而不是array

标签 java arrays exception arraylist syntax-error

该代码是为数组设计的,
我想在此代码中使用ArrayList,将代码ArrayList添加到源数组的下面。但是代码似乎无法读取ArrayList中的元素。我怎样才能实现呢?
它现在仅返回0,我猜那是因为它无法读取ArrayList中的元素?
这是我的代码。为什么会发生这种情况,我该如何解决?

import java.util.*; 
class RandomisedQuickSort 
{ 
    public static int N = 5; 
    public static int[] arr = new int[N]; 
    
    void random(int low,int high) 
    { 
    
        Random rand= new Random(); 
        int pivot = rand.nextInt(high-low) + low; 
        
        int temp1=arr[pivot]; 
        arr[pivot]=arr[high]; 
        arr[high]=temp1; 
    } 
    
    int partition(int arr[], int low, int high) 
    { 
        int pivot = arr[high]; 
    

        int i = (low-1);
        for (int j = low; j < high; j++) 
        { 
        
            if (arr[j] <= pivot) 
            { 
                i++; 

                int temp = arr[i]; 
                arr[i] = arr[j]; 
                arr[j] = temp; 
            } 
        } 

        int temp = arr[i+1]; 
        arr[i+1] = arr[high]; 
        arr[high] = temp; 

        return i+1; 
    } 

    void sort(int arr[], int low, int high) 
    { 
        if (low < high) 
        { 
            int pi = partition(arr, low, high); 

            sort(arr, low, pi-1); 
            sort(arr, pi+1, high); 
        } 
    } 

    static void printArray(int arr[]) 
    { 
        int n = arr.length; 
        for (int i = 0; i < n; ++i) 
            System.out.print(arr[i]+" "); 
        System.out.println(); 
    } 

    public static void main(String args[]) 
    { 
        //int arr[] = {10, 7, 8, 9, 1, 5}; 

        ArrayList<Integer> list = new ArrayList<>();
        
        for (int i = 1; i <= 10; i++) {
            list.add(i);
        }
        Collections.shuffle(list);
                    
        int n = arr.length; 
        
        RandomisedQuickSort ob = new RandomisedQuickSort(); 
        ob.sort(arr, 0, n-1); 

        System.out.println("sorted array"); 
        printArray(arr); 
    } 
}

最佳答案

您正在使用Integer[],但sort()printArray()期望int[]

void sort(int arr[], int low, int high) {...}
static void printArray(int arr[]) {..}
您可以通过这种方式将Arraylist转换为int[]并使用
 int[] arr = list.stream().mapToInt(i->i).toArray();

关于java - 使用arraylist而不是array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62778108/

相关文章:

java - Glassfish:HTTP 500 内部服务器错误无一异常(exception)

java - 来自 .Net 的压缩流并从 Java 读取它们的问题

java - Map 的参数化类型键

arrays - 如何修复 JSON 解析应用程序中的 'Index Out Of Range' 错误

python - 用另一个数组切片 numpy 数组

c++ - 异常在构造函数 try block 中被捕获并处理,但仍会再次被重新抛出

java - 创建 native 线程时出现 OutOfMemoryError

java - 向 Eclipse 编辑器插件添加语义突出显示

java - 用俄罗斯方 block 填充整个 2D 阵列(俄罗斯方 block 板),没有剩余空间(Java)

c# - 事件源异常 : No Free Buffers available from the operating system