我尝试将两个整数与以下情况进行比较,并得到意想不到的结果
当我做了以下时,打印了@@@.
class C {
static Integer a = 127;
static Integer b = 127;
public static void main(String args[]){
if(a==b){
System.out.println("@@@");
}
}
}
Run Code Online (Sandbox Code Playgroud)当我做了以下时,@@@没有打印出来.
class C {
static Integer a = 145;
static Integer b = 145;
public static void main(String args[]){
if(a==b){
System.out.println("@@@");
}
}
}
Run Code Online (Sandbox Code Playgroud)谁能告诉我可能是什么原因.
你正在比较对象的身份.对于低于128的值,Integer类会缓存其对象.这就是为什么它在第一个例子中是相同的.另一个例子是没有缓存的更高值.
正如@niklon指出的那样,缓存的边界也为-128.
可以使用VM arg调整上边框-Djava.lang.Integer.IntegerCache.high=4711.
在Peter的有趣博客文章中进一步阅读:http: //vanillajava.blogspot.co.uk/2012/01/surprising-results-of-autoboxing.html
您不是在比较ints,而是在比较对象以获得引用相等性.使用.equals,或使用类型int而不是Object.
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |