• Java趣味短码


    原文:http://www.ituring.com.cn/article/27186#jtss-tqq

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

    需求很简单。

    首先定义一个类

    classItem{publicint key;publicint l;publicint r;};

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

    publicstaticvoid main(String[] args){Item x;
        x =newItem();
        x.key =1;
        x.l =10;
        x.r =20;int i =0;if(x.key > i){
            i = x.l;}else{
            i = x.r;}
    
        i =0if( 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);

    第二个场景比较棘手!

    因为表达式不能被赋值。

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

    publicstatic<T>boolean to_(T s , T d){if(  s.getClass()!= d.getClass()){returnfalse;}
        d = s;returntrue;}

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

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

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

    如下是完整的代码。

    package tPackge;classItem{publicint key;publicint l;publicint r;};publicclass test01 {publicstatic<T>boolean to_(T s , T d){if(  s.getClass()!= d.getClass()){returnfalse;}
            d = s;returntrue;}/**
         * @param args
         */publicstaticvoid main(String[] args){Item x;
            x =newItem();
            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);}}}
    
    
  • 相关阅读:
    openlayers wfs获取要素
    ArcEngine 直连连接SDE
    arcgis中的 style和serverstyle
    C#开源大全
    C#+ArcEngine 序列化和反序列化AE对象
    C# lazy加载
    Testing 理论测试(三)
    软件开发模型种类(7)
    Testing理论测试题(二)
    Testing 理论测试题(一)
  • 原文地址:https://www.cnblogs.com/bjanzhuo/p/3576054.html
Copyright © 2020-2023  润新知