Wednesday, June 29, 2011

Few handy functions provided by Enum class

Suppose we have a following enum class :

public enum Weekdays {
MONDAY("Monday",1),TUESDAY("Tuesday",2),WEDNESDAY("Wednesday", 3),THURSDAY("Thursday",4),FRIDAY("Friday",5),SATURDAY("Saturday",6),SUNDAY("Sunday",7);

 private static HashMap<String,Weekdays> hm = new HashMap<String, Weekdays>();


static {
hm.put(MONDAY.getName(),MONDAY);
hm.put(TUESDAY.getName(),TUESDAY);
hm.put(WEDNESDAY.getName(),WEDNESDAY);
hm.put(THURSDAY.getName(),THURSDAY);
hm.put(FRIDAY.getName(),FRIDAY);
hm.put(SATURDAY.getName(),SATURDAY);
hm.put(SUNDAY.getName(),SUNDAY);
}

int val;
String name;

private Weekdays(String name,int val) {
this.val = val;
this.name = name;
}

public int getVal() {
return val;
}

public String getName() {
return name;
}

public static Weekdays getByName(String s) {
return hm.get(s);
}

//Test Class
public class TestEnum {
public static void main(String args[]) {
TestEnum t = new TestEnum();
t.badWay();
}

public void badWay() {
Weekdays w = Weekdays.getByName("Friday");
System.out.println(w.getName());
}
}

And, we are interested in finding required enum by name or val. What usually comes to mind is creating a static hashmap and use above function like getByName. This might be fine if you need to do fast lookup quite often.

Enum provides some handy functions like values and valueOf instead. findByVal below illustrates a alternative approach using these function :


import java.util.HashMap;
public enum Weekdays {
MONDAY("Monday",1),TUESDAY("Tuesday",2),WEDNESDAY("Wednesday", 3),THURSDAY("Thursday",4),FRIDAY("Friday",5),SATURDAY("Saturday",6),SUNDAY("Sunday",7);

int val;
String name;

private Weekdays(String name,int val) {
this.val = val;
this.name = name;
}

public int getVal() {
return val;
}

public String getName() {
return name;
}

public static Weekdays findByVal(int i) {
for(Weekdays w : Weekdays.values()) {
if(w.getVal()==i) return w;
}
return null;
}

}

//Test Class
public class TestEnum {
public static void main(String args[]) {
TestEnum t = new TestEnum();
t.goodWay1();
t.goodWay2();
t.goodWay3();
}

public void goodWay1() {
Weekdays w = Enum.valueOf(Weekdays.class, "FRIDAY");
System.out.println(w.getName());
}

public void goodWay2() {
Weekdays w = Weekdays.valueOf("FRIDAY");
System.out.println(w.getName());
}

public void goodWay3() {
Weekdays w = Weekdays.findByVal(3);
System.out.println(w.getName());
}
}

Sunday, June 26, 2011

Funny thing about Java thread

Other day, I was trying to store a thread reference which could be started whenever needed. To surprise, it threw IllegalThreadStateException. After searching I figured out that threads can be started only ones..rightly as javadoc says "It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."

So you have 3 options :
- Use thread suspend/resume
- Do not allow it to end, use Thread.sleep(time)
- Create new thread as needed