0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【.longValue() とは?Javaでの型変換】

0
Posted at

Java において .longValue() は、Integerラッパークラスのインスタンスを プリミティブな long 値に変換するメソッド です。

ラッパークラス(Integer, Double, Float, Long…)には .xxxValue() というメソッドがあり、それぞれ対象のプリミティブ型に変換できます。

たとえば、Spring Boot でリポジトリの主キー型を Long にしていた場合

UsersRepository.findById(Long id) // ← このメソッドは Long を期待している

でも自分が Integer 型(例:Integer userId = 5;)を渡してしまうと、こんなコンパイルエラーが…

java.lang.Integer cannot be converted to java.lang.Long

つまり、暗黙の型変換はされない…。 このときに活躍するのが .longValue():

usersRepository.findById(userId.longValue());

.longValue() の注意点!

.longValue() は ラッパークラスに対して使うメソッド なので、int などプリミティブ型には使えない。

int i = 100;
i.longValue(); // ❌ コンパイルエラー

その場合は、Integer に変換する必要があるらしい

Integer boxed = Integer.valueOf(i);
boxed.longValue(); // ✅ OK

変換対象の値が null だと NullPointerException が発生するので要注意!

まとめ

型  変換方法一覧
Integer → long .longValue()    
int → long 自動的にOK(暗黙拡張)
Long → long Long → long
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?