Skip to content

Instantly share code, notes, and snippets.

@kazuhito-m
Created March 19, 2015 10:08
Show Gist options
  • Save kazuhito-m/aa6290020efcf04b2170 to your computer and use it in GitHub Desktop.
Save kazuhito-m/aa6290020efcf04b2170 to your computer and use it in GitHub Desktop.
JavaでBooleanのvalueOf()とnewと定数との比較を行うサンプル。
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
/**
* BooleanのvalueOf()とnewと定数との比較を行うテスト。
* @author kauzhito_m
*/
public class BooleanPrimitiveAndBoxingTest {
@Test
public void ブーリアンのvalueOfとnewで同じ値になってくれるのか() {
Boolean valueOfBoolean = Boolean.valueOf("0");
Boolean newBoolean = new Boolean("0");
Boolean falseBoolean = Boolean.FALSE;
System.out.println(valueOfBoolean.toString() + " , " + valueOfBoolean.hashCode());
System.out.println(newBoolean.toString() + " , " + newBoolean.hashCode());
System.out.println(falseBoolean.toString() + " , " + falseBoolean.hashCode());
// ハッシュは一緒になるみたい。
assertThat(valueOfBoolean.hashCode() == newBoolean.hashCode() , is(true));
assertThat(newBoolean.hashCode() == falseBoolean.hashCode() , is(true));
// もちろん、eqaulsは同じになるやろね。
assertThat(valueOfBoolean.equals(newBoolean) , is(true));
// == 演算子では参照が違うみたい(ハッシュが同じになるだけでインスタンスは再利用している感じではないのだね)。
assertThat(valueOfBoolean == newBoolean , is(false));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment