有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

线程“main”Java中的csv Java ArrayList异常。lang.NegativeArraySizeException:28

我对排序算法有意见。我使用这个TimSort对https://www.geeksforgeeks.org/timsort/(Java)进行排序。例如,我在前2500行的循环中读取CSV文件

这是我的阅读代码:

    private void readFile(){
        try{
            int i = 0;
            BufferedReader csvReader = new BufferedReader(new FileReader(this.filename));
            while ((row = csvReader.readLine()) != null){
                String[] entry = row.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
                if(i > 0 && i <= 2500){
                    int price = Integer.parseInt(entry[5]);
                    entries.add(price);
                }
                i++;
            }
            csvReader.close();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

之后,我将通过以下方式将字符串转换为int[]数组列表:

public int[] convertArrayList(){
    ArrayList<Integer> arrayList = this.entries;
    int[] converted = new int[arrayList.size()];
    for(int i=1; i < converted.length; i++){
        converted[i] = arrayList.get(i);
    }
    return converted;
}

我主要有:

    private static synchronized void getPrices(){
        try{
            File dataset = new File("src/CSV/Schools.csv");
            CSVReader reader = new CSVReader(dataset.getCanonicalPath());
            prices = reader.convertArrayList();
        } catch(Exception e){
            e.printStackTrace();
        }
    }

并运行它:

    getPrices();
    int n = prices.length;
    System.out.println(n);

    Instant start = Instant.now();
    System.out.print("Given Array is\n");
    GFG.printArray(prices, n);
    Instant end = Instant.now();

    System.out.println("Time for executing the unsorted array: " + Duration.between(start, end).toNanos());


    GFG.timSort(prices, n);

    Instant start2 = Instant.now();
    System.out.print("\nAfter Sorting Array is\n");
    GFG.printArray(prices, n);
    Instant end2 = Instant.now();

    System.out.println("Time for executing the sorted array: " + Duration.between(start2, end2).toNanos());

现在事情是这样的 如果我运行此代码并将循环更改为I>;0&&;我<;=它在工作。但是如果我取一个更大的数字,比如2500或5000,我会得到以下错误:

Exception in thread "main" java.lang.NegativeArraySizeException: -28
at GFG.merge(TimSort.java:32)
at GFG.timSort(TimSort.java:111)
at Main.main(Main.java:27)

它引用了TimSort算法中的合并方法。。。我不能解决这个问题,有什么想法吗


共 (1) 个答案

  1. # 1 楼答案

    可能是因为您链接到的TimSort算法实现有缺陷

    List.sortCollections.sortArrays.sort(T[])都已使用timsort。不需要从随机站点复制代码来使用TimSort。实用程序方法java.util.Arrays.sort(int[])使用双枢轴排序。我假设它具有更好的性能特征,因此使用它来代替timsort

    如果您试图理解链接到的timsort代码,请忘记粘贴的所有代码,关注链接到的timsort impl,然后调试它