-3

Note: Not a duplicate of How do I compare strings in java as I am taking about going through some checks to determine if something is inheriting something something else

Is their a better and more efficient way to do this:

As you can see I am inputting 2 strings then checking them of on a list, as if current = three then it returns true for checking for one, two and three

NOTE: these values(one,two,three) are just placeholders for the example in my use their is no relation between them except that they have a different priority.

public boolean checker(String current, String check) {


    if (check.equals("one")) {
        if (current.equals("one") || current.equals("two")
                || current.equals("three")) {
            return true;
        }
    }
    if (check.equals("two")) {
        if (current.equals("two") || current.equals("three")) {
            return true;
        }
    }
    if (check.equals("three")) {
        if (current.equals("three")) {
            return true;
        }
    }
    return false;

}
Cœur
  • 37,241
  • 25
  • 195
  • 267
the133448
  • 75
  • 7
  • **Don't** test `String` equality with `==`. How is your logic different from `if (check.equals(current))`? – Elliott Frisch Dec 26 '14 at 01:59
  • 1
    You may want to use data that better represents your actual use case. Are these strings `one`, `two` and `three` the only possible set of strings? If so you can use `enum`s to represent them, replace `if` constructs with `switch-case`s and so on. – mystarrocks Dec 26 '14 at 02:08

3 Answers3

0

Here are a few pointers

  1. As Frisch mentioned in comments, use .equals rather than == for String comparison.

  2. Use switch/case

    switch (check) {
        case "one":
            if (current.equals("one")) return true;
        case "two":
            if (current.equals("two")) return true;
        case "three":
            if (current.equals("three")) return true;
    }
    

Apart from that, there doesn't seem to be much to do.

k_g
  • 4,333
  • 2
  • 25
  • 40
0

Two things.

  1. Don't check strings using equality. Use the .equals() method. You can call it off the string literal. So something like this. Calling it off the string literal is safe even with nulls, which is generally a good thing.

    if ("one".equals(check))
    
  2. You can take advantage of Java's short circuit operators && and ||

    if ("one".equals(check)) {
        if ("one".equals(current) || "two".equals(current) || "three".equals(current)) {
            return true;
        }
    }
    

Can become

if ("one".equals(check) && ("one".equals(current) || "two".equals(current) || "three".equals(current))) {
    return true;
}

Which will be evaluated from left to right. Since the "one".equals(check) is on the far most left, and is &&'ed with the rest of the statement, Java will bail out of the condition checking if "one".equals(check) is not true, and will not evaluate the rest of the statement.

Since you're just returning true or false, you can also take this a step further and reduce all of your if statements into a single one using De Morgan's laws (http://en.wikipedia.org/wiki/De_Morgan's_laws). Generally you state your boolean if statement in the way that is most natural to you, and then you start simplifying it by applying transformations that keep the logical if statement the same.

A good example of this is, stolen from the below link.

In the context of the main method's program body, suppose the following data is defined:

int score, min = 0, max = 20;
boolean bad, good;

Further suppose that a value is assigned to score, perhaps from a keyboard entry, and I would like to test, with a Boolean expression whether the score is a valid number or not. A good score is in the closed range [0 .. 20], which includes 0 and 20.

good = (score >= min && score <= max);

I would like to get the score from the keyboard in a do while loop, so that I can validate the entry. The logic in my control structure is to demand another entry for the score while the entry is bad. I have a definition of a good entry, and I will use definitions of operators and De Morgan's Law to help me write an expression that represents a bad entry.

good = (score >= min && score <= max); // original definition of good from the logic of my task 
good = !(score < min) && !(score > max); // by definition, >= means ! < , <= means ! >
good = !(score < min || score > max); // by De Morgan's' Law
bad = !good ; // bad is not good
bad = !!(score < min || score > max); // substituting for good
bad = score < min || score > max; // double negation is dropped

http://fcmail.aisd.net/~JABEL/1DeMorgansLaw.htm

Jazzepi
  • 5,259
  • 11
  • 55
  • 81
  • 1
    TBF, the `nested-if` is much more readable than the `&&` in this context. And there's typo on the method name - it's `equals`. – mystarrocks Dec 26 '14 at 02:10
  • I strongly disagree with you about that assertion of clarity. But this isn't a style guide, it's specifically a question about how to be "better and more efficient". I'm not sure if the compiler would be smart enough to extract the inner block out into a large boolean for you to create the type of short circuit operation as given in this answer, but if you have a long set of conditions to check, making sure that the first one that gets checked is a simple condition is a big priority. It's actually a mix of simplicity / chance to return false and stop the boolean chain, but that's extraneous. – Jazzepi Dec 26 '14 at 02:18
0

I would like to update you some thing. 1. We can apply switch cases only on primitive data types but not on objects. As string is object we can't use strings in case/switch statement.

I would like to suggest you to enums/maps in this case.

Please find the below sample programm how i implemented using maps.

 public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<String, Integer>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);

        String current = "one";
        String check = "one";
        if(map.get(check)<=map.get(current)){
            System.out.println("Our condition is success");
        }
    }

Instead of multiple comparison this is better.

---Santhosh