tohokuaikiのチラシの裏

技術的ネタとか。

Javaのプリミティブ型とObjectの違いをコードで

恥ずかしながら、Integerとintの比較とか分かってなかったので、実験しつつメモ。

Ideone.com - PuegZx - Online Java Compiler & Debugging Tool

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	public static void main (String[] args) throws java.lang.Exception
	{
		ArrayList<Long> l = new ArrayList<Long>();
		long l1 = 100;
		long l2 = 200;
		int l3 = 300;
		l.add(l1);
		l.add(l2);
//		l.add(l3); // ランタイムエラー
		Long y = new Long(200);
		System.out.println(l.contains(y)); // true
		long y2 = 100;
		System.out.println(l.contains(y2)); // true
		int y3 = 100;
		System.out.println(l.contains(y3)); // false
//		System.out.println((Long)y3); コンパイルエラー
		System.out.println(y2 == y3); // true
	}
}


なるほどー。

  1. int と longは比較できる
  2. int と Integer は比較できない。
  3. ArrayListではプリミティブ型のlongをオブジェクト型のLongに自動変換してる
  4. ArrayListは long はLongに自動変換してくれるけど、int → long → Longとはいかない。