java 中的异常是哪种类型: 注意:Demo.java 使用未经检查或不安全的操作。注意:使用 -Xlint:unchecked 重新编译以获取详细信息

Which type of Exception is this in java : Note: Demo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details

import java.util.*;

class Demo {

    public static void main(String args[])
    {
        TreeSet t= new TreeSet();
        t.add("A");
        t.add("B");
        t.add("z");
        t.add("Z");
        t.add("M");
        t.add("N");
        System.out.println(t);
    }
}

Demo.java 使用未经检查或不安全的操作。 注意:使用 -Xlint 重新编译:未选中详细信息*

编译时我遇到了这个错误

这不是错误,而是警告。

class TreeSet 是一个参数化的 class (TreeSet<T>) 但你声明它是原始的,这意味着你没有指定条目的类型.

这意味着编译器无法推断类型,也无法检查您放入其中的内容。

声明参数化的正确方法 classes:

如果您声明类型:

TreeSet<String> t = new TreeSet<>(); //<-- the compiler knows you will add strings
t.add("someString"); //<-- fine
t.add(1); //<-- won't let you compile

...编译器将强制执行类型检查,如果您错误地添加了不是您声明的类型的内容,则不会让您编译。

您的做法(原始类型声明):

如果您不声明类型(就像您现在所做的那样):

TreeSet t = new TreeSet(); //<-- the compiler cannot know what you will add
t.add("someString"); // <-- fine
t.add(1); // <-- fine... but is it really fine?

...那么当你在其中添加任何内容时它都不会抱怨。但是,这可能会导致错误,这就是为什么编译器会警告您正在做一些不正确的事情。

As a side note: this is not true just for TreeMap<T>, but for any parametrized class/interface which is declared without inferring the parameter(s) type(s)