在Java中用于表达式的别名

huangapple go评论73阅读模式
英文:

Alias for expressions in java

问题

在Java中,您可以使用方法或lambda表达式来避免重复编写条件。以下是您提供的示例的Java代码:

// 使用方法
public class Main {
    public static void main(String[] args) {
        if (cond(2, 5, 8)) {
            // 条件成立时执行的代码
        }
        if (cond(3, 6, 9)) {
            // 条件成立时执行的代码
        }
    }
    
    public static boolean cond(int i, int j, int k) {
        return (i == 2) && (j == 5) && (k == 8);
    }
}

或者,您还可以使用lambda表达式来实现类似的功能:

public class Main {
    public static void main(String[] args) {
        Condition cond258 = (i, j, k) -> (i == 2) && (j == 5) && (k == 8);
        Condition cond369 = (i, j, k) -> (i == 3) && (j == 6) && (k == 9);

        if (cond258.check(2, 5, 8) || cond369.check(3, 6, 9)) {
            // 条件成立时执行的代码
        }
    }
    
    interface Condition {
        boolean check(int i, int j, int k);
    }
}

这两种方法都可以帮助您避免重复编写条件,并使代码更加清晰可读。

英文:

I have a if condition in java that reoccurs at many places in the code. I want to avoid writing the whole condition again and again. In C, I could have done this with #define

#define cond ((i==2) && (j==5) && (k==8))

int main() {
	if(cond)
}

How can I achieve the same in java? I can probably create another method that evaluates this condition -

  main() {
    	if(cond())
    }

cond() {
    return (i==2) && (j==5) && (k==8);
}

but I wanted to know if I can avoid creating another function.


UPDATE -

I realized I should add more details/edit to support my argument. Lets say I have 2 conditions and I want to check both-

 #define cond258 ((i==2) && (j==5) && (k==8))
 #define cond369 ((i==3) && (j==6) && (k==9))

I can create 2 functions -

cond258(i, j, k) {
        return (i==2) && (j==5) && (k==8);
    }
cond369(i, j, k) {
        return (i==3) && (j==6) && (k==9);
    }

this doesn't look like a good approach to me. Both functions are doing sort of similar things so they should be converted to single function -

cond(i, j, k, first, second, third) {
        return (i==first) && (j==second) && (k==third);
}

but then that makes my if condition unreadable -

if(cond(i, j, k, 2, 5, 8) || cond(i, j, k, 3, 6, 9))

so instead if I could have some aliases, I could simply write this as

if(cond258 || cond369)

答案1

得分: 4

我相信你不能这样做,而不编写另一个函数,或者至少不建议/实际。为条件语句编写另一种方法实际上是在重构你的代码,分解条件表达式 在这种情况下。

英文:

I believe you can't do so without writing another function, or at least, not advisable/practical. Writing another method for conditional statement is actually refactoring your code, Decompose conditional in this case.

答案2

得分: 1

你可以像这样做。

private static int i = 2;
private static int j = 5;
private static int k = 8;
private static Supplier<Boolean> cond = () -> i == 2 && j == 5 && k == 8;

public static void main(String[] args) {
    System.out.println(cond.get()); // 输出 true
    k = 11;
    System.out.println(cond.get()); // 输出 false
}
  • 我将它们设为静态,以便可以在任何上下文中使用(静态或实例)。
  • 这些变量不能是局部变量,因为 Lambda 表达式中的局部值必须是有效 final。
  • 它们将与实例化包含它们的类的其他类共享。

这是一个使用实例字段的示例。

int ii = 2;
int jj = 5;
int kk = 8;

Supplier<Boolean> cond = () -> ii == 2 && jj == 5 && kk == 8;

public static void main(String[] args) {
    ThisClass tc = new ThisClass();

    // 静态上下文,因此需要限定
    System.out.println(tc.cond.get()); // 输出 true
    tc.kk = 11;
    System.out.println(tc.cond.get()); // 输出 false
    tc.foo();
}

public void foo() {
    // 实例方法,因此 cond 和 kk 不需要限定
    kk = 8;
    System.out.println(cond.get()); // true
}
英文:

You could do something like this.

private static int i = 2;
private static int j = 5;
private static int k = 8;
private static Supplier&lt;Boolean&gt; cond  = ()-&gt;i == 2 &amp;&amp; j == 5 &amp;&amp; k == 8;	
public static void main(String[] args) {
    System.out.println(cond.get()); // prints true
    k = 11;
    System.out.println(cond.get()); // prints false
}
  • I made them static so they could be used in any context (static or instance).
  • The variables can't be local since local values in a lambda must be effectively final.
  • And they will be shared with other classes that instantiate the class that contains them.

Here is an example using instance fields.

int ii = 2;
int jj = 5;
int kk = 8;

Supplier&lt;Boolean&gt; cond = () -&gt; ii == 2 &amp;&amp; jj == 5 &amp;&amp; kk == 8;
	
public static void main(String[] args) {

    ThisClass tc = new ThisClass();

    // static context so they need to be qualified.
    System.out.println(tc.cond.get()); // prints true
    tc.kk = 11;
    System.out.println(tc.cond.get()); // prints false
    tc.foo();
}
public void foo() {
    // instance method so cond and kk do not need to be qualified
    kk = 8;
    System.out.println(cond.get()); // true
}

</details>



# 答案3
**得分**: 0

这是我的解决方法 -

创建了一个新的 Triplet 类 -

```java
public class Triplet<F, S, T> {
    
    public F first;
    public S second;
    public T third;
    
    @Override
    public boolean equals(Object obj) {

        if (obj instanceof Triplet<?, ?, ?>) {
            
            Triplet<?, ?, ?> triplet = (Triplet<?, ?, ?>) obj;            
            return (this.first.equals(triplet.first) && this.second.equals(triplet.second) && this.third.equals(triplet.third));
        } 
        else 
            return false;
    }

    
    public Triplet (F first, S second, T third) throws NullPointerException {
        if(first==null|| second==null || third==null)
            throw new NullPointerException("无法使用 null 值创建对象,第一个、第二个或第三个值");
        this.first = first;
        this.second = second;
        this.third = third;
    }    
}

创建了静态的 triplets -

public static final Triplet<Integer, Integer, Integer> triplet258 = new Triplet<Integer, Integer, Integer>(2, 5, 8);
public static final Triplet<Integer, Integer, Integer> triplet369 = new Triplet<Integer, Integer, Integer>(3, 6, 9);

我的条件判断改为 -

Triplet<Integer, Integer, Integer> myTriplet = new Triplet<Integer, Integer, Integer>(i, j, k);

if(myTriplet.equals(triplet258) || myTriplet.equals(triplet369))
英文:

This is how I solved this -

created a new class Triplet -

public class Triplet &lt;F, S, T&gt; {
	
	public F first;
	public S second;
    public T third;
	
	@Override
	public boolean equals(Object obj) {

		if (obj instanceof Triplet &lt;?,?,?&gt;) {
			
			Triplet &lt;?, ?, ?&gt; triplet = (Triplet &lt;?, ?, ?&gt;) obj;			
			return (this.first.equals(triplet.first) &amp;&amp; this.second.equals(triplet.second) &amp;&amp; this.third.equals(triplet.third));
		} 
		else 
			return false;
	}

	
	public Triplet (F first, S second, T third) throws NullPointerException {
		if(first==null|| second==null || third==null)
			throw new NullPointerException(&quot;Can&#39;t create object with null values for first or second or third&quot;);
		this.first = first;
		this.second = second;
		this.third = third;
	}	
}

Created static triplets -

public static final Triplet&lt;Integer, Integer, Integer&gt; triplet258 = new Triplet&lt;Integer, Integer, Integer&gt;(2, 5, 8);
public static final Triplet&lt;Integer, Integer, Integer&gt; triplet369 = new Triplet&lt;Integer, Integer, Integer&gt;(3, 6, 9);

my if condition changes to -

Triplet&lt;Integer, Integer, Integer&gt; myTriplet = new Triplet&lt;Integer, Integer, Integer&gt;(i, j, k);

if(myTriplet.equals(triplet258) || myTriplet.equals(triplet369))

huangapple
  • 本文由 发表于 2020年9月10日 02:26:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63817495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定