有 Java 编程相关的问题?

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

创建对象时,是否需要java为两个菱形运算符指定数据类型?

我正在用Java(Android Studio)创建ArrayAdapter对象 是否需要将字符串数据类型添加到菱形运算符的两侧?有人能解释一下吗

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<"here">(this,安卓.R.layout.simple_list_item_1,numbersInChars);

共 (2) 个答案

  1. # 1 楼答案

    javagenerics tutorial包含以下关于回答您问题的菱形操作符的解释:

    In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context.

    编译器可以确定String类型参数来调用构造函数,因为您在赋值ArrayAdapter<String> arrayAdapter = ...的左半部分指定了它,所以不需要指定它

  2. # 2 楼答案

    不需要,您不需要在右侧指定它。但是,如果您在那里指定,它不会造成任何伤害。请在https://docs.oracle.com/javase/tutorial/java/generics/types.html阅读有关钻石的更多信息。以下是同一页中的一个示例:

    Box<Integer> integerBox = new Box<>();
    

    如您所见Integer未在右侧指定。但是,如果您愿意,也可以按如下方式编写:

    Box<Integer> integerBox = new Box<Integer>();