Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayUtils.contains is returning false for string already present

Tags:

java

arrays

Why my OUTPUT is showing NOOOO?

UserRole.java

public enum UserRole {
    ROLE_X("ROLE_X"), //
    ROLE_Y("ROLE_Y"), //
    ROLE_Z("ROLE_Z"), //
    OTHER_X("OTHER_X"),
    OTHER_Y("OTHER_Y"),
    OTHER_Z("OTHER_Z");


    private final String name;

    private UserRole(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public boolean hasName(String name) {
        return this.name.equals(name);
    }

    public static UserRole[] ROLES = { ROLE_X, ROLE_Y, ROLE_Z };
    public static UserRole[] OTHER = { OTHER_X, OTHER_Y, OTHER_Z };

}

TestCode.java

import java.text.ParseException;
import org.apache.commons.lang.ArrayUtils;

public class TestCode{
    public static void main(String[] args) throws ParseException {

        String name = "ROLE_X";

        if(ArrayUtils.contains(UserRole.ROLES, name)) {
            System.out.println("---ROLES---");
        } else {
            System.out.println("NOOOO");
        }



    }
}

OUTPUT: NOOOO

like image 201
My God Avatar asked Jan 17 '26 22:01

My God


1 Answers

Because an enum is not a String.

You have an array of enum instances, but you're searching for a String, which will never be equals() to an enum.

Use:

UserRole.valueOf(str)

and catch IllegalArgumentException, which is thrown when the string doesn't match an instance.


Most of your enum class can be deleted:

  • you don't need the name field at all. Every enum has a .name() method that returns the enum instance name as a string
  • every enum class has a .values() method that returns all instances as an array
like image 121
Bohemian Avatar answered Jan 19 '26 17:01

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!