通用程序设计

1.将局部变量的作用域最小化 
 

2.for-each循环优先于传统的for循环

		String str = "abc";
		for(int i = 0; i < str.length(); i++){
			//code
		}
		/**
		 * 节省了每次迭代str.length()方法的开销
		 */
		for(int i = 0, n = str.length(); i < n; i++){
			//code
		}

3.如果需要精确的答案,请避免使用float和double

System.out.println(1.00 - 9 * .10);//结果为0.09999999999999998

		double funds = 1.00;
		int count = 0;
		for(double price = .10; funds >= price; price += .10){
			funds -= price;
			count++;
		}
		
		
		System.out.println(count + " items bought.");
		System.out.println("Change: $" + funds);

3 items bought.
Change: $0.3999999999999999

结果本来应该是4的,可是这里只有3,是因为double类型的运算操作产生了误差导致

		final BigDecimal TEN_CENTS = new BigDecimal(".10");
		
		int count = 0;
		BigDecimal funds = new BigDecimal("1.00");
		for(BigDecimal price = TEN_CENTS; funds.compareTo(price) >= 0; price = price.add(TEN_CENTS)){
			count++;
			funds = funds.subtract(price);
		}
		
		System.out.println(count + " items bought.");
		System.out.println("Money left over: $" + funds);
4 items bought.
Money left over: $0.00

//这种方法结果才是正确的
使用BigDecimal有两个缺点:与使用基本运算类型相比,计算很不方便,而且很慢

对于使用货币,可以选用int或者long类型,以分为单位而不是以元为单位

		int count = 0;
		int funds = 100;
		for(int price = 10; funds >= price; price += 10){
			count++;
			funds -= price;
		}
		
		System.out.println(count + " items bought.");
		System.out.println("Money left over: $" + funds);
4 items bought.
Money left over: $0

4.基本类型优先于装箱基本类型

基本类型通常比装箱基本类型更节省时间和空间

		long startTime = System.currentTimeMillis();
		Long sum = 0L;
		for(long i = 0; i < Integer.MAX_VALUE; i++){
			sum += i;
		}
		long endTime = System.currentTimeMillis();
		long spendTime = (endTime - startTime) / 1000;
		System.out.println("程序运行时间:" + spendTime + "秒");
程序运行时间:24秒
		long startTime = System.currentTimeMillis();
		long sum = 0L;
		for(long i = 0; i < Integer.MAX_VALUE; i++){
			sum += i;
		}
		long endTime = System.currentTimeMillis();
		long spendTime = (endTime - startTime) / 1000;
		System.out.println("程序运行时间:" + spendTime + "秒");
程序运行时间:6秒
这里差别就在Long sum = 0L和long sum = 0L,上一种情况每一次运算都会进行拆箱装箱,严重影响了效率
PS:除非必须要用到装箱基本类型,否则优先使用基本类型

5.

public class Demo1 {
	static Integer i;
	public static void main(String[] args) {
		if(i == 42){
			System.out.println("Unbelievable");
		}
		
	}
}
这里程序运行会报空指针异常,i 对象是引用类型对象,当i == 42运行时,i 会进行拆箱操作,由于 i 这是为null ,所以会出现空指针异常

PS:空指针异常一定是有某个引用类型对象值为null导致


猜你喜欢

转载自blog.csdn.net/xy87940020/article/details/78337066