2016-03-31 11 views
19

私は、コードを使用しています:`System.out.println(null);`はなぜ "println(char [])の型がPrintStreamエラーの型にあいまいですか?

System.out.println(null); 

をそれがエラーを示している。

The method println(char[]) is ambiguous for the type PrintStream 

はなぜnullObjectを表すものではありませんか?

+2

'System.out.println((Object)null); ' –

+1

[nullを渡すことができません();アンドロイド4.0のAsyncTaskのメソッド](http://stackoverflow.com/questions/10679739/unable-to-pass-null-to-execute-method-of-asynctask-in-android-4-0) – Raedwald

+1

httpも参照してください://stackoverflow.com/questions/13033037/how-is-an-overloaded-method-chosen-when-a-parameter-is-the-literal-null-value – Raedwald

答えて

25

参照型を受け入れるPrintStream 3つのprintln方法があり - println(char x[])println(String x)println(Object x)は。

nullを渡すと、3つすべてが適用されます。メソッドのオーバーロードルールは、最も具体的な引数タイプを持つメソッドを好むので、println(Object x)は選択されません。

コンパイラは、最初の2つの間で選択することができない - println(String x) & println(char x[])を - Stringchar[]およびその逆よりも特異的ではないからです。

特定の方法を選択する場合は、必要な型にnullをキャストします。例えば

System.out.println((String)null); 
+1

私はこの概念を理解しています。しかし、答えの完全性のために、JLSはなぜ 'char []'と 'String'が同じように具体的な理由がどこかに指定されていますか?結局のところ、 'char'はプリミティブであり、' String'はオブジェクトです。 – Magnilex

+11

@Magnilex charはプリミティブですが、char []はオブジェクトです。 char []はStringのサブクラスではなく、Stringはchar []のサブクラスではありません。したがって、2つのどちらもより具体的ではありません。 – Eran

+3

@KannanThangaduraiは、 'char x []'を 'char [] x'と書くことができることに注意してください - 多くのもの(例えば、[Googleのスタイルガイド](https:// google。github.io/styleguide/javaguide.html#s4.8.3.2-array-declarations))は、 'x'の型が' char'ではなく 'char []'なので、後者の方が好きです。タイプをまとめておくと、読みやすくなります。 –

7

あなたが呼び出す場合System.println(null)取りするかを決めることはできないとコンパイラ(char []StringObject引数で)複数の候補の方法があります。

修正
明示的キャストをnullに追加します。

System.out.println((Object)null); 

またはnull object patternを使用してください。 JLS 4.1 The Kinds of Types and Values

There is also a special null type, the type of the expression null, which has no name.
Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type.
The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type.
The null reference can always be assigned or cast to any reference type

In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type

から


Why does't null represent Object?

Object(読み取りと割り当てられる)に変換することができるがそうnullのタイプは、Objectありません。

関連する問題