I have a list of enums like the below -
List<Status> statusList;
Status is defined as below
enum Status { YES , NO , MAYBE }
The list contains
Status stat = Status.YES;
statusList.add(stat);
I have a variable
Status statusVar = Status.YES;
I am trying to a comparison like below but it is not working as I guess it is comparing the references. The below returns false. Can you please suggest a solution?
statusList.contains(statusVar)
EDIT: Below is the code that is not working. Status is string not Enum
import java.util.ArrayList;
import java.util.List;
public class Test {
private enum Status {
YES , NO , MAYBE
}
public static void main (String[] args){
List<Status> statusList = new ArrayList<Status>();
String status = "YES";
statusList.add(Status.YES);
if(statusList.contains(status)){
System.out.println(" Yes ");
} else {
System.out.println(" No ");
}
}
}
If you are performing a contains, it will be much more efficient if you use an EnumSet
Set<Status> status = EnumSet.of(Status.YES);
assert status.contains(Status.YES);
However, List<Status>
will also work.
You are right it does compare the reference, but this will only fail if you have
Status
is actually different.Status
which you can do using Unsafe.allocateInstance(Status.class)
What is more likely is you are not testing what you think you are and the situation isn't exactly as you have described.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With