Java的数据类型的挑选

1 int类型和Integer类型的区别

在Java中的int类型只适用于数值计算, 而Integer是类,可以应用于任何需要类的地方。
Integer的应用场景包括:

  • int类型因为默认值为0,而Integer默认值为NULL,所以如果没有赋值的话,Integer是可以看出来的,而int类型无法区分int=0和未赋值两种情况,应用场景为JSP中表单数据的表示和Hibernate中对数据库中数据的表示
  • Integer是对象,比如我可以在List, Map中存储Integer。这会比较方便。因为List,Map的基本类型都为object。
  • Integer中还包括Integer.MAX_VALUE, Integer.MIN_VALUE等数据和class类型的object类型的类型转换的类
    比如: static int parseInt(String s), long longValue()

2 double,float类型操作

double类型(8字节)和float类型(4字节)都是进行浮点数操作,1.234默认是double类型,1.234F才是float类型
但是在进行金融计算时候不适合出现舍入误差,而float类型在操作的时候会经常出现误差,比如0.9 - 0.1 != 0.8。而是0.79999995。所以这个时候应该使用BigDecimal
BigDecimal的用法的好处

import java.math.*;  
  
public class Libai {  
    public static void main(String args[]){  
        BigDecimal volumn = new BigDecimal("0");  
          
        for (int i=0; i<5;  i++){             
            volumn = volumn.add(new BigDecimal("1"));  
            volumn = volumn.divide(new BigDecimal("2"));  
        }  
          
        System.out.print(volumn);  
    }  
}
//最后结果为:0.96875..
 
posted @ 2012-05-16 10:34  Jack204  阅读(521)  评论(0编辑  收藏  举报