JAVA代码优化(持续记录中...)

1、用while来累加一个不超过特定值的数

原方法:

        while (tempSum <= tempMax - (tempValue + 1)) {
            tempValue++;
            tempSum += tempValue;
            System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
        } // Of while
        System.out.println(tempSum);

改进后:

        while (tempSum <= tempMax) {
            tempValue++;
            tempSum += tempValue;
            System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
        } // Of while
        tempSum -= tempValue;
        System.out.println(tempSum);

(由于是实现的累加,会出现在倒数第二个数满足条件,但依旧会执行累加,即得到的sum总是会大于指定的数值。原方法是在判断条件上改变[即每次循环都会执行一次基本算数运算],而改进后的代码只用在最后进行一次基本算数运算)

2、在用String记录输出数组时:用for循环遍历数组,除最后一个数据外,需要在每个数据后面加逗号隔开。

原方法:

        for (int i = 0; i < length; i++) {
            if (i != length - 1) {
                resultString += data[i] + ",";
            } else {
                resultString += data[i];
            }
        }

改进后:

        for (int i = 0; i < length - 1; i++) {
            resultString += data[i] + ",";
        }

        resultString += data[length - 1];

(改进后的代码不需要每次for循环就进行一次判断,进行同样次数的累加,却省去了每次的判断)

3、链表,根据给定元素找元素位置的方法。

原方法:

    public int locate(int paraValue) {
        int tempPosition = -1;

        Node tempNode = header.next;
        int tempCurrentPosition = 0;
        while (tempNode != null) {
            if (tempNode.data == paraValue) {
                tempPosition = tempCurrentPosition;
                break;
            }

            tempNode = tempNode.next;
            tempCurrentPosition++;
        }

        return tempPosition;
    }

改进后:

    public int locate(int paraValue) {
        
        Node tempNode = header.next;
        int tempCurrentPosition = 0;
        while (tempNode != null) {
            if (tempNode.data == paraValue) {
                return tempCurrentPosition;
            }
            tempNode = tempNode.next;
            tempCurrentPosition++;
        }
        return -1;

    }

在原来的基础上,while循环里判断为true时,直接return当前的位置,遍历完了没有找到,则执行最后的return -1。(tip:在自己写方法时,有时循环中的break可以用return替换。)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值