Java ラッパークラス
Java ラッパークラス
ラッパークラスは、プリミティブデータ型(int、booleanなど)をオブジェクトとして使う方法を提供します。
次の表は、プリミティブ型と同等のラッパークラスを示しています。
| プリミティブ データ型 | ラッパークラス |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| boolean | Boolean |
| char | Character |
例えば、ArrayListのようなプリミティブ型が使えない(リストはオブジェクトしか格納できない)Collectionオブジェクトを扱う場合など、ラッパークラスを使わなければならないことがあります。
例
ArrayList<int> myNumbers = new ArrayList<int>(); // 無効
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // 有効
ラッパー オブジェクトの作成
ラッパー オブジェクトを作成するには、プリミティブ型の代わりにラッパー クラスを使用します。値を取得するには、オブジェクトを出力するだけです。
例
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}
オブジェクトを操作しているため、特定のメソッドを使用して特定のオブジェクトに関する情報を取得できます。
たとえば、次のメソッドを使用して、対応するラッパー オブジェクトに関連付けられた値を取得します。intValue()、byteValue()、shortValue()、longValue()、floatValue()、doubleValue()、charValue()、booleanValue().
この例は、上記の例と同じ結果を出力します。
例
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
もうひとつの便利な方法は、ラッパーオブジェクトを文字列に変換するtoString()です。
次の例では、Integer型をStringに変換します。Stringクラスのlength()メソッドを使って文字列の長さを出力します。
例
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}
}