型と予約語

Java

Java基本型の注意点

★偶数と奇数の判断

i%2 == 1 ? "奇" : "偶"; × -1%2の場合にバグ

i%2 == 0 ? "偶" : "奇"; 〇

★型の範囲を考慮

public static final int LIGHT_SPEED = 30 * 10000 * 1000;

long distance = 1L * LIGHT_SPEED * 60 * 8;

public static final int LIMIT = 2000;

public void method(int order){

int current = 1000;

if(order > 0 && order + current <= LIMIT){ ←order=2147483647の時にバグ

// do something

}

}

※int型に対するチェックは、0、intのMax、intのMinが必須

public static int getAbsAdd(int x, int y) {

return Math.abs(x) + Math.abs(y);

}

public static int getAbsAdd(int x, int y) {

if(x == Integer.MIN_VALUE || y == Integer.MIN_VALUE) {

throw new IllegalArgumentException();

}

int absX = Math.abs(x);

int absY = Math.abs(y);

if(absX + absY > Integer.MAX_VALUE) {

throw new IllegalArgumentException();

}

return absX + absY;

}

★BigDecimal 金額計算

整数で最大9桁まで(10億未満):int

整数で最大10桁以上:long

小数で:BigDecimal

小数の比較

int i = 1;

String s = Double.valueOf(i / 1000.0).toString();

if(s.equals("0.001")){

...

}

int i = 1;

BigDecimal d = new BigDecimal( Double.valueOf(i / 1000.0).toString() );

if(d.compareTo(new BigDecimal("0.001")) == 0){

...

}

BigDecimal d = new BigDecimal(12345);

BigDecimal r = new BigDecimal(0.0018 * 3);

BigDecimal i = d.multiply(r).setScale(2, RoundingMode.HALF_EVEN);

四捨五入のモード

・ROUND_UP

・ROUND_DOWN

・ROUND_CEILING Math.round

・ROUND_FLOOR

・HALF_UP 四捨五入

・HALF_DOWN

・HALF_EVEN Banker's Round

BigDecimalのデメリット

・float、doubleに比べて遅い

・使いづらい

BigDecimal a = new BigDecimal("0.01");

BigDecimal a = new BigDecimal(0.01); × 誤差あり

if(a.compareTo(b) == 0)

a = b.add(c);

a = b.subtract(c);

a = b.multiply(c);

a = b.divide(c, ROUNDING_MODE);

ROUNDING_MODE まるめ方式

ROUND_UP 切り上げ;

ROUND_DOWN 切り捨て

ROUND_HALF_UP 四捨五入

★プリミティブ型のWrapper Types

public static int method(List<Integer> list){

int count = 0;

for(int i : list){

count += i; ←バグ

}

for(Integer i : list){

count += (i != null) ? i : 0; ←nullチェックが必要

}

return count;

}

HashSet<Short> s = new HashSet<Short>();

for(short i = 0; i < 100; i++){

s.add(i);

// s.remove(i - 1); ×

s.remove((short)(i - 1)); ○

}

★Wrapper Typesの比較

int ii = 100;

Integer i = new Integer(ii);

Integer j = new Integer(ii);

boolean b = i==j; false

boolean b = i>j; false

boolean b = i<j; false

※i.compareTo(j)或いはi.equals(j)を利用すべき

i = ii;

j = ii;

或いは

i = Integer.valueOf(ii);

j = Integer.valueOf(ii);

※i = ii;とi = Integer.valueOf(ii);同じ

boolean b = i==j; true 127の場合

boolean b = i==j; false 128の場合

valueOfメソッド中に整数プールが存在するため、

-128~127間の整数は整数プールから取得

以外の整数はnewでインスタンス作成

Boolean b1 = new Boolean("true");

Boolean b2 = new Boolean("true");

boolean b = b1==b2; false

Boolean b1 = true;或いはBoolean b1 = Boolean.True;

Boolean b2 = true;或いはBoolean b2 = Boolean.True;

boolean b = b1==b2; true

★Javaのinstanceofについて

※比較対象間は必ず継承・実装の関係がある

boolean b = "String" instanceof Object; true

boolean b = new String() instanceof String; true

boolean b = new Object() instanceof String; false

boolean b = 'A' instanceof Character; コンパイルエラー 基本型×

boolean b = null instanceof String; false

boolean b = (String)null instanceof String; false キャストでもnullのため

boolean b = new Date() instanceof String; コンパイルエラー

boolean b = new GenericClass<String>().isDateInstance(""); false String⇒Object

class GenericClass<T>{

public boolean isDateInstance(T t){

return t instanceof Date; // Object instanceof Dateと同じ

}

}

★JavaのDecimalFormatクラスについて

数値を金額として表示

DecimalFormat df = new DecimalFormat("\#,###");

String rlt = df.format(10000); // \10,000

DecimalFormat df = new DecimalFormat("\u00A4"); // 通貨記号で

String rlt = df.format(10000); // \10000

Locale.setDefault(Locale.US);

DecimalFormat df = new DecimalFormat("\u00A4");

String rlt = df.format(10000); // $10000

Locale.setDefault(Locale.JAPAN);

DecimalFormat df = new DecimalFormat("\u00A4\u00A4"); // 国際通貨記号で

String rlt = df.format(10000); // JPY10000

小数値をパーセントとして表示

DecimalFormat df = new DecimalFormat("#,###%");

String rlt = df.format(0.01); // 1%

数値の桁をそろえる

DecimalFormat df = new DecimalFormat("00000");

String rlt = df.format(123); // 00123

String rlt = df.format(1234567); // 1234567

DecimalFormat df = new DecimalFormat("0.000");

String rlt = df.format(0.12); // 0.120

String rlt = df.format(0.1234); // 0.123

String rlt = df.format(0.1236); // 0.124 四捨五入

C#

JavaScript

PHP

★型のチェック

gettype()

is_bool()

is_int() エイリアス:is_integer() / is_long()

is_double() エイリアス:is_real() / is_float()

is_string()

is_array()

is_resource()

is_object()

is_null()

is_numeric() 数値または数値文字列の場合にTRUE

is_scalar() スカラー(論理値、整数、浮動小数点数、文字列)の場合にTRUE

★null vs empty()

$var; // null

$var = null; // null

unset($var); // null

is_null($var) true

!isset($var) true issetとis_null逆

empty($var) true null値はempty

!$var true null値はfalse

//false・emptyとみなされる値

$var = false;

$var = 0;

$var = 0.0;

$var = '';

$var = '0';

$var = array();

$var = null;

$var = $noset;

Java

★型変換

// String ⇔ int

String str = String.valueOf(20);

int i = Integer.parseInt(str);

// List ⇔ 配列

List<String> list = new ArrayList<String>();

String[] array = list.toArray(new String[0]);

String[] array = {"aaa", "bbb", "ccc"};

List<String> list = Arrays.asList(array);

// List ⇔ Set

Set set = new HashSet(new ArrayList());

List list = new ArrayList(new HashSet());

// Map → List/Set

List list = new ArrayList(map.values());

Set set = new HashSet(map.values());

Set set = new HashSet(map.keySet());

// util.Date ⇒ sql.Date

java.util.Date utilDate = new java.util.Date();

java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

// String ⇔ Date

方法1

try {

java.util.Date date = java.text.DateFormat.getDateInstance().parse("2012/09/23");

} catch (ParseException e) {

e.printStackTrace();

}

方法2

SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

try {

java.util.Date date = format.parse("2012/09/23");

} catch (ParseException e) {

e.printStackTrace();

}

★Javaの乱数について

import java.util.UUID;

UUID id = UUID.randomUUID();

import java.util.Random;

private static final String TARGET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxzy0123456789";

private static String method() {

Random rnd = new Random();

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 10; i++) {

int val = rnd.nextInt(TARGET.length());

sb.append(TARGET.charAt(val));

}

return sb.toString();

}

commons-langのRandomStringUtils

import org.apache.commons.lang3.RandomStringUtils;

randomAscii(10)

randomAlphabetic(10)

randomNumeric(10)

random(10,"012345abcdef") // 指定した文字列

random(1,"123456789") + randomNumeric(9) // 0から始まらない

random(RandomUtils.nextInt(3)+1,"12345678") // 長さもRandom

セキュアではない乱数

方法1 0 <= Random.nextInt(int n) < n

// [min, max]の範囲の乱数を生成

public static int createRandom(int min, int max) {

Random random = new Random();

return random.nextInt(max - min + 1) + min;

}

方法2 0.0 <= Math.random() < 1.0

int random = (int) (Math.random() * 11);

高品質の乱数

import java.security.SecureRandom;

try {

SecureRandom number = SecureRandom.getInstance("SHA1PRNG");

for (int i = 0; i <10; i++) {

// [0, 10]の範囲の乱数を生成

System.out.println(number.nextInt(11));

}

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

.NET 2.0とJava SE6のキーワード一覧比較

※1:gotoとconstはJavaのキーワードだが、使われない。

※2:C#の[NonSerialized] = Javaのtransient。