Java 比较传递的null int字符串和整数构造函数
考虑以下两种说法Java 比较传递的null int字符串和整数构造函数,java,Java,考虑以下两种说法 Integer integer = new Integer(null); String string = new String(null); 第二个给出编译错误说明 Cannot resolve constructor `String(null)` 现在整数和字符串都有接受String的构造函数。那么为什么字符串给出编译错误,而不是整数呢 第一个打电话 public Integer(String s) throws NumberFormatExcepti
Integer integer = new Integer(null);
String string = new String(null);
第二个给出编译错误说明
Cannot resolve constructor `String(null)`
现在整数和字符串都有接受String
的构造函数。那么为什么字符串给出编译错误,而不是整数呢
第一个打电话
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
所以我期待字符串1也会调用
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
我无法理解这是如何发生的,编译器被迫在其中一个而不是另一个中出现编译错误。问题是,特别是对
新字符串(null)
的调用不明确,这意味着存在多个潜在的匹配构造函数,因此编译器无法决定要调用哪个构造函数
…这正是标准Oracle java编译器已经告诉您的:
Test.java:5:错误:对字符串的引用不明确
新字符串(空);
^
字符串中的构造函数字符串(StringBuffer)和字符串中的构造函数字符串(StringBuilder)都匹配
1错误
给我一个不同的错误
这是一个不明确的调用,因为公共字符串(char value[])
和公共字符串(String original)
构造函数都匹配
您可以尝试:
String string = new String((String) null);
或
解决歧义
另一方面,
Integer
类只有一个构造函数,它采用单个引用类型-public Integer(String s)
,因此没有歧义。如果String String=new String(null)代码>存在歧义错误。此构造函数是歧义的@谢谢大家,我认为编译器应该给出一些更准确的错误,如歧义错误
。你说的“应该”是什么意思?是的@它给出的都是肯定的,但必须理解的重要一点是,当传递给没有关联类型的方法时,null
。实际上,null
本身是一个单独的实体/类型。这些方法在编译时绑定并检查签名匹配。由于null
既可以是String
也可以是char[]
,如果是String
,编译器会尖叫
String string = new String((String) null);
String string = new String((char[]) null);