我在做這些網上的Java測試之一,有人問我這樣一個問題:java.lang.Object o = 1; //爲什麼編譯?
問:請說明正確的分配:
Long l = 1;
Double d = 1;
Integer i = 1;
String s = 1;
Object o = "1";
System.out.println(o);
o = 1;
System.out.println(o);
請自己嘗試一下,你再往前走了。
那麼我可以告訴你,我聽錯了,我調查了一下,發現:
//Long l = 1; //cannot widen and then box
Long ll = 1L;//no need to widen, just box
//Double d = 1;//cannot widen and then box
Double dd = 1d;//no need to widen, just box
Integer i = 1;//no need to widen, just box
//String s = 1;//cannot do implicit casting here
Object o = "1";//this compiles and is just plain weird
System.out.println(o);//output is 1
o = 1;//this also compiles and is also weird
System.out.println(o);//output is 1
誰能告訴我爲什麼:
Object o = 1;
和Object o = "1";
編譯和輸出1在兩種情況下,這讓我感到困惑。
非常感謝
哇,謝謝你的回答,但我必須告訴你,我現在覺得這麼愚蠢,我應該知道這一點。 – Ramo 2010-02-27 08:11:05
@Ramo:不要問你不知道的東西會很愚蠢:-) – Grundlefleck 2010-02-27 14:24:24