Created
October 12, 2012 01:33
-
-
Save aya-eiya/3876850 to your computer and use it in GitHub Desktop.
staticメンバー変数のスコープにまつわる地雷を踏み抜いた話 ref: http://qiita.com/items/8d8a04f4e99ec43c5169
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 久々に触ったJavaでこういうことをやってしまったと言う話 | |
public final class MyClassOne{ | |
private static final ArrayList<String> myList = new ArrayList<String>() | |
//-------^これがミス | |
public MyClassOne add(String str){ | |
myList.add(str) | |
return this | |
} | |
public int size(){ | |
myList.size() | |
} | |
} | |
def myClassOne1 = new MyClassOne() | |
def myClassOne2 = new MyClassOne() | |
assert(myClassOne1.add("hoge").size()==1) | |
assert(myClassOne2.add("hoge").size()==1) // これが失敗する | |
// なぜならmyListは | |
// MyClassOneのインスタンス全てで | |
// 共有されているから実際のサイズは2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment