---
title: "Java趣味短码"
author: "何不笑"
date: "2013-01-24T21:45:46Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-01-24T21:46:56Z"
id: 1775397
url: "https://wait7758521.iteye.com/blog/1775397"
---

原文：[http://www.ituring.com.cn/article/27186#jtss-tqq](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 =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);
```

第二个场景比较棘手！

因为表达式不能被赋值。

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

```
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);}}}


```