简体   繁体   English

java.lang.ClassCastException:class java.util.TreeMap 无法转换为 class java.lang.Comparable

[英]java.lang.ClassCastException: class java.util.TreeMap cannot be cast to class java.lang.Comparable

I receive the following error when attempting to run my java program尝试运行我的 java 程序时收到以下错误

Exception in thread "main" java.lang.ClassCastException: class java.util.TreeMap cannot be cast to class java.lang.Comparable (java.util.TreeMap and java.lang.Comparable are in module java.base of loader 'bootstrap')
    at java.base/java.util.TreeMap.compare(TreeMap.java:1569)
    at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:776)
    at java.base/java.util.TreeMap.put(TreeMap.java:785)
    at java.base/java.util.TreeMap.put(TreeMap.java:534)
    at exportsParser.exportsMap(exportsParser.java:53)
    at exportsParser.main(exportsParser.java:28)

The applicable code:适用代码:

import edu.duke.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.*;
import java.util.*;
import java.util.TreeMap;
import java.util.Iterator;

public class exportsParser{

    void println(Object obj){
        System.out.println(obj);
    }

    /* The rather involved pattern used to match CSV's consists of three
     * alternations: the first matches aquoted field, the second unquoted,
     * the third a null field.
     */
    private final static Pattern csv_pattern = Pattern.compile("\"([^\"]+?)\",?|([^,]+),?|,");

    public static void main(String[] argv) throws IOException {
        //println(csv_pattern);
        exportsParser parser = new exportsParser();
        BufferedReader reader = new BufferedReader(new FileReader("./exports_small.csv"));
        parser.exportsMap(reader);
    }
    public TreeMap<String, TreeMap<TreeMap<String,String> ,TreeMap<String, String>>> exportsMap(BufferedReader reader) throws IOException{

        if(reader.readLine() == null) return null;

        TreeMap<String, TreeMap<TreeMap<String,String>, TreeMap<String,String>>> exportsTable = new TreeMap<>();
        TreeMap<String, String> products = new TreeMap<>();
        TreeMap<String, String> value = new TreeMap<>();
        TreeMap<TreeMap<String,String>,TreeMap<String,String>> exportsData = new TreeMap<>();

        int countryIndex = 0;

        ArrayList<String> exportsList = new ArrayList<String>();
        String line;

        try{
            while((line = reader.readLine()) != null){
                exportsList = parse(line);

                String countryName = exportsList.get(0);
                products.put("items", exportsList.get(1));
                value.put("total", exportsList.get(2));
                println(products);
                println(value);
                exportsData.put(products, value);
                println(exportsData);

    //              exportsTable.put(countryName,exportsData);
                println(exportsTable);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        reader.close();
        return exportsTable;
    }

    /* Parse one line.
     * @return List of Strings, minus their double quotes
     */
    public ArrayList<String> parse(String line) {
        ArrayList<String> list = new ArrayList<String>();
        Matcher mat = csv_pattern.matcher(line);
        // For each field
        while (mat.find()) {
            String match = mat.group();
            if (match == null)
                break;
            if (match.endsWith(",")) {  // trim trailing ,
                match = match.substring(0, match.length() - 1);
            }
            /*if (match.startsWith("\"")) { // assume also ends with
              match = match.substring(1, match.length() - 1);
              }*/
            if (match.length() == 0)
                match = null;
            list.add(match);
        }
        return list;
    }
}

To clarify, the issue arises when attempting to put the TreeMap data of products and value in exportsData.需要澄清的是,当尝试将产品和价值的 TreeMap 数据放入 exportsData 时会出现问题。 Same is applicable when attempting to add exportsData to the exportsTable correlating its key (Country) to the exportsData (Value).当尝试将 exportsData 添加到 exportsTable 并将其键(国家/地区)与 exportsData(值)相关联时,同样适用。 I understand what the errors means, I just have no idea as to how to fix it.我明白这些错误意味着什么,我只是不知道如何解决它。 Additionally libraries are not allowed (Purpose is to understand the flow of input data into "rows/columns" and experiment with Trees, HashMaps, etc)此外,不允许使用库(目的是了解输入数据流向“行/列”并试验 Trees、HashMap 等)

Additionally, I cannot use a database for this as this is a requirement to manually do this.此外,我不能为此使用数据库,因为这是手动执行此操作的要求。 However what is not a requirement is using TreeMaps of course.但是,当然不需要使用 TreeMaps。 We are allowed to experiment with the various Collection classes.我们可以试验各种 Collection 类。

I have spent a while trying to get this to work but I have run out of thoughts and forum pages to read now.我花了一段时间试图让它发挥作用,但我现在已经没有足够的想法和论坛页面来阅读了。 Eventually, this would be ideal to make it cater towards larger CSV files of unknown columns.最终,这将是让它适应更大的 CSV 未知列文件的理想选择。 However, for the practice run, we have been given the information before hand, hence the indexing in the code above.然而,对于练习运行,我们已经事先获得了信息,因此在上面的代码中进行了索引。

CSV data: CSV 数据:

Country,Exports,Value (dollars)
Germany,"motor vehicles, machinery, chemicals","$1,547,000,000,000"
Macedonia,"tobacco, textiles","$3,421,000,000"
Madagascar,"coffee, vanilla, shellfish","$864,800,000"
Malawi,"tea, sugar, cotton, coffee","$1,332,000,000"
Malaysia,"semiconductors, wood","$231,300,000,000"
Namibia,"diamonds, copper, gold, zinc, lead","$4,597,000,000"
Peru,"copper, gold, lead, zinc, tin,  coffee","$36,430,000,000"
Rwanda,"coffee, tea, hides, tin ore","$720,000,000"
South Africa,"gold, diamonds, platinum","$97,900,000,000"
United States,"corn, computers, automobiles, medicines","$1,610,000,000,000"

This is my first time using the above so it is prone to beginner errors.这是我第一次使用上述内容,因此很容易出现初学者错误。

Check javadoc .检查javadoc To cite - The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.引用 - The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Natural ordering of keys means key must implement Comparable .键的自然排序意味着键必须实现Comparable Your keys are of type TreeMap , which does not have natural ordering - it does not implement Comparable .您的键是TreeMap类型,它没有自然顺序 - 它没有实现Comparable Naturally this leads to ClassCastException .这自然会导致ClassCastException

If you really must use TreeMap as key for your TreeMap, you must provide a Comparator to TreeMap constructor:如果您真的必须使用 TreeMap 作为 TreeMap 的键,则必须为 TreeMap 构造函数提供一个比较器:

Comparator<TreeMap<String,String>> comparator = implement it;
TreeMap<TreeMap<String,String>,TreeMap<String,String>> exportsData = new TreeMap<>(comparator);

Seeing that your data is coming from a csv file, i would suggest to parse it to some custom class. It would be much more readable, and it will be easier to implement Comparable , or Comparator if needed.看到您的数据来自 csv 文件,我建议将其解析为一些自定义的 class。它会更具可读性,并且如果需要的话,实现ComparableComparator也会更容易。

Edit: You don't actually need 2 maps - for exports and value, it complicates thing more that needed.编辑:您实际上不需要 2 张地图 - 对于出口和价值,它使所需的事情变得更加复杂。 Those can be put in a single map. Keys are values from the first line in csv(or other keys, as in your case) and values are corresponding values from the parsed line.这些可以放在一个 map 中。键是 csv 中第一行的值(或其他键,如您的情况),值是解析行中的对应值。 So you have:所以你有了:

Map<String, String> lineData;

Country may also be part of this map(if you need it).国家也可能是这张地图的一部分(如果你需要的话)。 Normally it's this map, which will be rerpesented by your custom class, but it looks like your task is to work with collections, so i won't delve into that.通常是这个 map,它将由您的自定义 class 重新分配,但看起来您的任务是使用 collections,所以我不会深入研究。

Since you want to map country names to data, now you need another map - keys will be string(country name) and values the map containing line data from above.由于您想要将 map 国家名称转换为数据,现在您需要另一个 map - 键将是字符串(国家名称)并且值 map 包含来自上面的行数据。

All of that can be stored in a list(you can store anything in a list).所有这些都可以存储在列表中(您可以将任何内容存储在列表中)。 I'm leaving to you figuring out the exact way to implement it.我将留给您找出实施它的确切方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java.lang.ClassCastException: 不能转换为 java.lang.Comparable - java.lang.ClassCastException: cannot be cast to java.lang.Comparable java.lang.ClassCastException:java.util.HashMap无法强制转换为java.lang.Comparable - java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparable Getting java.lang.ClassCastException: class lambda.Student cannot be cast to class java.lang.Comparable while using FlatMap - Getting java.lang.ClassCastException: class lambda.Student cannot be cast to class java.lang.Comparable while using FlatMap 类不能强制转换为 java.lang.Comparable - Class cannot be cast to java.lang.Comparable java.lang.ClassCastException:尝试排序List时,java.util.LinkedHashMap无法转换为java.lang.Comparable异常 - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.lang.Comparable exception when trying sort a List java.lang.ClassCastException: org.postgresql.util.PGobject 不能转换为 java.lang.Comparable; UUID转换器内部 - java.lang.ClassCastException: org.postgresql.util.PGobject cannot be cast to java.lang.Comparable; inside UUIDconverter 线程“主”java.lang.ClassCastException 中的异常:javafx.util.Pair 无法转换为 java.lang.Comparable - Exception in thread “main” java.lang.ClassCastException: javafx.util.Pair cannot be cast to java.lang.Comparable 列表到TreeSet的转换产生:“ java.lang.ClassCastException:MyClass无法转换为java.lang.Comparable” - List to TreeSet conversion produces: “java.lang.ClassCastException: MyClass cannot be cast to java.lang.Comparable” MyClass无法强制转换为java.lang.Comparable:java.lang.ClassCastException - MyClass cannot be cast to java.lang.Comparable: java.lang.ClassCastException &#39;java.lang.ClassCastException:资源无法强制转换为java.lang.Comparable&#39; - 'java.lang.ClassCastException: Resource cannot be cast to java.lang.Comparable'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM