Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<Enum> contains String

Tags:

java

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 ");
        }

    }

}
like image 294
Punter Vicky Avatar asked Jan 08 '23 15:01

Punter Vicky


1 Answers

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

  • multiple ClassLoaders and the Class Status is actually different.
  • you create new instances of the 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.

like image 111
Peter Lawrey Avatar answered Jan 19 '23 12:01

Peter Lawrey