JavaでStringをInteger(またはint)に変換する一般的な手法について説明します。
String text = "456";
// 方法1:parseIntを使用
int number1 = Integer.parseInt(text);
// 方法2:valueOfを使用
Integer number2 = Integer.valueOf(text);
// 方法3:new演算子を使用(非推奨)
Integer number3 = new Integer(text); // 非推奨、古いスタイル
各変換方法の違い
| メソッド | 戻り値タイプ | ラッピング有無 | 使用推奨度 | 仕組みの説明 |
|---|---|---|---|---|
parseInt |
int |
なし | 推奨 | 直接文字列を解析してint型に変換 |
valueOf |
Integer |
あり | 推奨 | 実際にはparseInt()を使い、自動ラッピングを行う |
new Integer(text) |
Integer |
あり | 非推奨 | 毎回新しいオブジェクトを作成し、キャッシュを利用しないため性能が悪い |
内部処理の詳細(主にparseIntについて)
以下はInteger.parseInt(String s)の簡略化されたコードです:
public static int convertToInt(String s) throws NumberFormatException {
if (s == null) throw new NumberFormatException("null");
int result = 0;
boolean negativeFlag = false;
int index = 0, length = s.length();
char firstChar = s.charAt(0);
if (firstChar == '-') {
negativeFlag = true;
index++;
}
while (index < length) {
int digit = s.charAt(index++) - '0';
if (digit < 0 || digit > 9) throw new NumberFormatException();
result = result * 10 + digit;
}
return negativeFlag ? -result : result;
}
s.charAt(i) - '0':ASCII値を利用して文字を数字に変換。- 文字ごとに逐次計算を行い、結果を構築。
- 負数もサポート。
- 無効な数字文字の場合、例外を投げる。
オートボクシングとキャッシュ機構(valueOfの特徴)
Integer val = Integer.valueOf("456");
この場合、まずInteger.parseInt("456")が実行され、その後ラッピングが行われます:
return Integer.valueOf(parsedIntResult);
キャッシュプールの仕組み:
範囲[-128, 127]内の整数はキャッシュされるため、同一オブジェクトが返されます。
Integer x = Integer.valueOf(127);
Integer y = Integer.valueOf(127);
System.out.println(x == y); // true
Integer z = Integer.valueOf(128);
Integer w = Integer.valueOf(128);
System.out.println(z == w); // false
よくある質問と回答
| 質問 | 回答 |
|---|---|
parseIntとvalueOfの違い? |
一つはintを返し、もう一つはIntegerを返し、後者はオートボクシングを行う。 |
| どの方法が推奨されるか? | valueOfはオブジェクト操作に適し、parseIntは軽量で元のデータ型に最適。 |
Integer.valueOf()にはキャッシュがあるか? |
範囲[-128, 127]内で同じオブジェクトを返す。 |
なぜnew Integer()は非推奨なのか? |
毎回新規オブジェクトを作成し、メモリを浪費するため。 |
関連知識
- 整数から文字列への変換方法:
String str = String.valueOf(456);
String str2 = Integer.toString(456);