Posts

Showing posts with the label enums

Checking if a String is contained in an Enum Set in O(1)

Image
Clash Royale CLAN TAG #URR8PPP Checking if a String is contained in an Enum Set in O(1) Let's say I have an enum like the following: public enum Utils { UTIL_1, UTIL_2, ... UTIL_n } Now, I have Set<Utils> myUtils , which contains a bunch of these enum entries. Some other module (on which I don't have any control) gives me one such util name (say " UTIL_i ") as a String. I need to check if it is contained in the set myUtils . Is there any way to perform this operation in O(1)? I understand, I could change the set to be a set of Strings, and then do a .contains() on that, but I want to keep it as a last resort. Set<Utils> myUtils UTIL_i myUtils Update : Following the suggestions in the answer, I tried a little experiment. I created a small code snippet to generate a java file which is an enum of a fixed size. I tried with size 1000, 2500, 5000. An enum of size 10000 showed me the error The code for the static initializer is exceeding the 65535 bytes lim...

Java Enum why static line executes only once?

Image
Clash Royale CLAN TAG #URR8PPP Java Enum why static line executes only once? The result is: 1 3 1 3 1 3 2 The constructor runs for A,B and for C (3 times). But if you use static keyword it runs only once. What is the reason of this? And why does this line executes last? enum Enums { A, B, C; { System.out.println(1); } static { System.out.println(2); } private Enums() { System.out.println(3); } } public class MainClass { public static void main(String args) { Enum en = Enums.C; } } By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.