简体   繁体   English

是否有更有效的方法来比较If语句中的3个以上的项目?

[英]Is there a more efficient way to compare 3+ items in an If statement?

I am writing a program for a class assignment and I want to compare multiple items in an array for equivalence. 我正在编写一个类赋值的程序,我想比较一个数组中的多个项目以获得等价。 My statement basically looks like: 我的陈述基本上是这样的:

if (a == b && b == c && c == d && d == e && e == f) {
   // do stuff
}

This condition seems incredibly verbose, and I am wondering if there's a shorter way to write this. 这种情况似乎令人难以置信的冗长,我想知道是否有更短的方式来写这个。

This may appear to be verbose , but at least it is reasonably efficient and clear . 这可能看起来很冗长 ,但至少它是合理有效和清晰的

Don't overdo it with optimizing code for brevity. 为简洁起见,请不要过度使用优化代码。

You could easily make a helper function 你可以很容易地做一个辅助功能

boolean allEqual(Object ... objs) {
    for(int i = 1; i < obj.length; i++) {
      if (!objs[i].equals(objs[0])) {
        return false;
      }
    }
    return true;
}

But this will create additional objects; 但这会产生额外的对象; in particular with primitive values: 特别是原始值:

if (allEqual(1.1,2.1,3.1,4.1))

will create 5 objects, that need to be garbage collected. 将创建5个对象,需要进行垃圾回收。

Make sure you actually want == and not equals . 确保你真的想要==而不是equals

My suggestion is to create a set and if its size is one then all elements are equal, otherwise not: 我的建议是创建一个集合,如果它的大小是1,那么所有元素都是相等的,否则不是:

public static < E > boolean areAllEqual( E[] inputArray ){
    Set<E> mySet = new HashSet<E>(Arrays.asList(inputArray));
    return mySet.size() == 1;
}    

Following is complete code example: 以下是完整的代码示例:

import java.util.*;
public class HelloWorld{
    public static < E > boolean areAllEqual( E[] inputArray ){
        Set<E> mySet = new HashSet<E>(Arrays.asList(inputArray));
        return mySet.size() == 1;
    }    
     public static void main(String []args){
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'H', 'H', 'H', 'H' };

        System.out.println("It should work");
        if (areAllEqual(intArray))
            System.out.println("inarray Yes");
        else
            System.out.println("inarray No");

        if (areAllEqual(doubleArray))
            System.out.println("doubleArray Yes");
        else
            System.out.println("doubleArray No");

        if(areAllEqual(charArray))
            System.out.println("charArray  Yes");
        else
            System.out.println("charArray  No");                            
     }
}

output: 输出:

It should work
inarray No
doubleArray No
charArray  Yes  // all elements in char array are eq

This could be done in Java 8 the following, given that you already have an array: 鉴于您已经有了一个数组,这可以在Java 8中完成:

int[] numbers = {1, 2, 3, 4, 5};
if (Arrays.stream(numbers).allMatch(i -> (i == numbers[0]))) {
    //they are equal
}

What it does is: 它的作用是:

  • It encapsulates your array in an IntStream (it does not create extra objects, apart from the IntStream ) 它封装在您的阵列IntStream (它不会从创建额外的对象,除了IntStream
  • It checks if all objects return true on the IntPredicate . 它检查所有对象是否在IntPredicate上返回true。
  • The IntPredicate is i -> (i == numbers[0]) , which maps i to (i == numbers[0]) . IntPredicatei -> (i == numbers[0]) ,它将i映射到(i == numbers[0])

It would be advised to encapsulate this in a helper method, and you'd want to early bail if the array is empty, like this: 建议将其封装在一个辅助方法中,如果数组为空,你需要提前保释,如下所示:

public static boolean allEquals(final int[] input) {
    return (input.length > 0 && Arrays.stream(input).allMatch(i -> i == input[0]));
}

This depends though on whether it should return true or false if there's no input... Is everything equal then? 这取决于它是否应该返回truefalse如果没有输入......那么一切都相等吗?

Please note that you'd need to make this code for all primitives you are using. 请注意,您需要为正在使用的所有原语创建此代码。 As an extra, you can also provide a generic version: 另外,您还可以提供通用版本:

public static <T> boolean allEquals(final T[] input) {
    return (input.length > 0 && Arrays.stream(input).allMatch(i -> i.equals(input[0])));
}

Now when you do not have a suitable structure, meaning they are most likely just variables, then you will need to decide whether you are needing the extra performance or can live with the overhead of passing them in as an varargs input, that implicitely creates an array, the code for that would be really similar: 现在,当你没有合适的结构时,意味着它们很可能只是变量,那么需要决定是否需要额外的性能,或者可以承担将它们作为varargs输入传递的开销,这意味着产生了一个数组,其代码将非常相似:

public static <T> boolean allEquals(final T... input) {
    return (input.length > 0 && Arrays.stream(input).allMatch(i -> i.equals(input[0])));
}

You can almost certainly live with the extra overhead, only in very performance critical applications, you need to wary if your method gets executed a load of times. 几乎可以肯定,只有在性能非常关键的应用程序中才需要额外的开销,如果你的方法被执行了很多次,你需要警惕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM