| English | 意味 |
|---|---|
| wrapper class/ˈræpə klæs/ | ラッパークラス |
| autoboxing/ˌɔːtəʊˈbɒksɪŋ/ | 自動ボックス化 |
| unboxing/ʌnˈbɒksɪŋ/ | アンボックス化 |
Boxing a primitive
- Some Java structures (like
ArrayList) hold objects, not primitives. - A wrapper class 包装类 wraps a primitive in an object:
Integerwrapsint,Doublewrapsdouble. Integer boxed = Integer.valueOf(5);puts theint5inside an object.- Wrappers let primitives live where only objects are allowed.
Autoboxing and unboxing
- Java converts automatically — autoboxing 自动装箱 and unboxing 自动拆箱.
Integer x = 5;autoboxes5;int y = x;unboxes it back.- So
list.add(5)works even though the list holdsIntegerobjects. - You rarely write
Integer.valueOfby hand — autoboxing does it.
Why ArrayList needs them
ArrayList<Integer>holdsIntegerobjects, because generics require a reference type.- You can't write
ArrayList<int>— primitives aren't objects. - Autoboxing lets you add and read plain
ints conveniently. Double,Boolean, etc. play the same role for their primitives.
Compare wrappers with equals
- Two
Integerobjects should be compared with.equals(), not==. ==compares references;.equals()compares the wrapped values.- (Java caches small Integers, so
==sometimes seems to work — don't rely on it.) - The same "use
.equals()for objects" rule fromStringapplies here.
Wrappers are objects, so compare their values with .equals(), not ==. == tests reference identity; for two Integer objects with the same value it can be false. And you can't parameterize a collection with a primitive — it's ArrayList<Integer>, never ArrayList<int>. Autoboxing bridges the gap so you can still add plain ints.
Wrappers with an ArrayList:
ArrayList<Integer> nums = new ArrayList<Integer>();nums.add(5);— theint5is autoboxed into anInteger.int first = nums.get(0);— theIntegeris unboxed back toint.
A wrapper class (Integer, Double, Boolean) wraps a primitive in an object so it can go where objects are required — like an ArrayList<Integer> (you can't write ArrayList<int>). Autoboxing and unboxing convert automatically. Compare wrapper objects with .equals(), not ==.
オートボックス化とアンボックス化
int ↔ Integer の変換は自動的に発生します。
int を包むラッパークラスはどれですか?
難易度 1/5 · 100 コイン + 今日初回完了時に小ボーナス付与
Integer は int を包み、Double は double を包みます。
なぜ int の ArrayList を declaring する際は ArrayList
難易度 1/5 · 100 コイン + 今日初回完了時に小ボーナス付与
ArrayList
2つの Integer オブジェクトを比較するには、以下を使うべきです...
難易度 1/5 · 100 コイン + 今日初回完了時に小ボーナス付与
ラッパークラスはオブジェクトなので、値を比較するには .equals() を使うべきです。
nums.add(5) では、int 5 が自動的に Integer へボックス化(autoboxing)されます。
難易度 1/5 · 100 コイン + 今日初回完了時に小ボーナス付与
オートボックス化はプリミティブ型をラッパーオブジェクトに変換します。
プリミティブをオブジェクトに包むクラスは___クラス(単一単語)です。
難易度 1/5 · 100 コイン + 今日初回完了時に小ボーナス付与
Integer、Double、Boolean はラッパークラスです。