【问题标题】:Use an arraylist instead of array使用数组列表而不是数组
【发布时间】:2020-07-07 14:56:43
【问题描述】:

代码是为数组设计的, 我想在这段代码中使用 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); 
    } 
}

【问题讨论】:

  • 如果你使用的是 Eclipse,你不应该在没有确保它首先编译的情况下运行你的程序。这似乎是一个简单的语法错误
  • 你能告诉我们语法错误出现在哪里吗?我找不到它。将arr 设为int[] 即可解决问题
  • 你是想在代码中使用数组列表,还是只传递数组列表的值?

标签: java arrays exception arraylist syntax-error


【解决方案1】:

您正在使用 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();

【讨论】:

  • @user 你觉得int[] arr = list.toArray(new int[0]);这行得通吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-29
  • 2021-10-09
  • 2016-09-07
  • 2017-05-24
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多