Java 代码简化系列 (一)

Java趣味短码 - (第一节)

今天跟公司的童鞋聊天的时候,谈到了关于短码和代码的精简的方式,所以整理出来。

需求很简单。

首先定义一个类

class Item{
    public int key;
    public int l;
    public int r;
};

然后主函数的场景大概是这样

public static void main(String[] args) {
    Item x;
    x = new Item();
    x.key = 1;
    x.l = 10;
    x.r = 20;

    int i = 0;

    if (x.key > i){
        i = x.l;
    }else{
        i = x.r;
    }

    i = 0;
    if ( x.key > i){
        x.l = i;
    }else{
        x.r = i;
    }
}

这里面有两个子场景,就是接下来要讨论的。

子场景1

    if (x.key > i){
        i = x.l;
    }else{
        i = x.r;
    }

子场景2

    if ( x.key > i){
        x.l = i;
    }else{
        x.r = i;
    }
  • 子场景1 的规律是 左面的值都是一样的,都是赋值给i

  • 子场景2 的规律是 右面的值都是一样的,都是用i赋给别的变量。

那么我们如何来简化实现这两类场景呢?

第一个场景很简单,可以如下优化:

i = ( x.key >i ? x.l : x.r);

第二个场景比较棘手!

因为表达式不能被赋值。

那么我们需要一个传值函数。

public static <T> boolean to_(T s , T d){
    if(  s.getClass() != d.getClass() ){ return false; }
    d = s;
    return true;
}

有了如上函数我们就可以这样写

boolean r = ( x.key >i ? to_(i,x.l) : to_(i,x.r));

r是一个结果值用来检测类型是否正确。

如下是完整的代码。

package tPackge;


class Item{
    public int key;
    public int l;
    public int r;
};

public class test01 {
    public static <T> boolean to_(T s , T d){
        if(  s.getClass() != d.getClass() ){ return false; }
        d = s;
        return true;
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        Item x;
        x = new Item();
        x.key = 1;
        x.l = 10;
        x.r = 20;

        int i = 0;

        if (x.key > i){
            i = x.l;
        }else{
            i = x.r;
        }
        System.out.println(x.l);
        System.out.println(x.r);
        System.out.println(i);
        System.out.println("--------------------------");       
        i = ( x.key >i ? x.l : x.r);
        System.out.println(x.l);
        System.out.println(x.r);
        System.out.println(i);
        /*
        if ( x.key > i){
            x.l = i;
        }else{
            x.r = i;
        }
        */
        System.out.println("--------------------------");
        i = 0;
        //if ( x.key > i ) { x.l = i; } else { x.r = i; } 


        System.out.println(x.l);
        System.out.println(x.r);
        if ( ( x.key >i ? to_(i,x.l) : to_(i,x.r)) ){ System.out.println(i); }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值