I am gradually completing the CodingBat exercises for Java. Here is the one I just did:Given an array of ints, return true if it contains no 1's or it contains no 4's. Here is my code:public boolean no14(int[] nums) {    int oneCount = 0;    int fourCount = 0;    for (int i = 0; i < nums.length; i++) {        if (nums[i] == 1) {            oneCount++;        }        if (nums[i] == 4) {            fourCount++;        }    }    if (oneCount > 0 && fourCount > 0) {        return false;    }    return true;}Now, I am pretty unfamiliar with arrays, so I would just like to know if there is a simpler/shorter way of finding such information without setting a count for each number? Perhaps using a regular expression?
Return true if the elements of an array do not contain one or the other
java;beginner;array
In JDK there's nothing, but with Guava you could doList<Integer> list com.google.common.primitives.Ints.asList(nums);return !(list.contains(1) && list.contains(4));Obviously, converting int[] to something like ArrayList<Integer> would be a performance disaster. Fortunately, there's nothing like this, instead there's a class implementing the List interface by accessing the primitive array. Bulk-methods like contains are optimized and lead to a simple loop with no boxing inside.But seriously, feel free to stick with your loop, as there's not always such a trick available. What you could improve:You need no xxxCount, a simple boolean containsXxx would do. But this is no problem, having the count may be useful sometimes.You could use an early return. Whenever you find a 1, you can check if you have already a 4 and return false if so.The only part I dislike isif (oneCount > 0 && fourCount > 0) {    return false;}return true;You surely meanreturn oneCount == 0 || fourCount == 0;If performance was very important (which it rarely is), I'd try thisint i = 0;int missing;for (; ; i++) {    if (i == nums.length) {        return true;    } else if (num[i] == 1) {        missing = 4;        break;    } else if (num[i] == 4) {        missing = 1;        break;    }}for (; i < nums.length; i++) {    if (nums[i] == missing) {        return false;    }}return true;But as you can see, it's terribly long and not very readable. When embedded in a real code it may also be slower (due to inlining limit or whatever).