これらのオンライン Java テストの 1 つを行っていたところ、次の質問を受けました。
Q: 正しい割り当てを示してください:
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を出力しますが、これは私を困惑させます。
どうもありがとう