Monday, January 23, 2012

Java enum - constant-specific method implementations

This is a one of the interesting feature with java enum introduced with java 1.5. Normally We are using java enum to define some set of constants which enhance code readability and provides compile time type safety and more. If We want to define some behaviors specific to each of the constants define in enum, How Can We do it? 

There is a way to associate a different behavior with each enum constant.Declare an abstract method in the enum type, and override it with a concrete method for each constant in a constant-specific class body. Here is an example.

/**
 * @author semikas
 *
 */
public enum Operation {

 PLUS {
      @Override
      double apply(double x, double y) {
          return x + y;
      }
 },
 MINUS {
       @Override
       double apply(double x, double y) {
           return x - y;
       }
 },
 TIMES {
      @Override
      double apply(double x, double y) {
           return x*y;
      }
 },
 DIVIDE {
       @Override
       double apply(double x, double y) {
           return x/y;
       }
 };

 abstract double apply(double x, double y);
}

Thursday, January 12, 2012

String reverse algorithm

I went for a java technical interview recently and they told me to write simple java method to get the reverse of a given string object. I used java's 'StringBuilder' class and it provides 'reverse()' method. I guess, I am correct. They smiled and went one step ahead. They told me to do the same thing without using any java providing function and write my own function to reverse the string. I wrote that as well. Finally they told me to write it using the recursive algorithm. I was little stuck and they moved to next question. 

I came home and though for a algorithm to reverse the string. I came up with this solution. 

We can get the character array from the given string and characters can be swapped in the following manner.



public String reverseStr(String s) {
    char arr[] = reverseStr(0, s.toCharArray());
    return new String(arr);
}
private char[] reverseStr(int charIndex, char[] arr) {

    if (charIndex > arr.length - (charIndex+1)) {
      return arr;
    }
    char temp = arr[charIndex];
    arr[charIndex] = arr[arr.length - (charIndex+1)];
    arr[arr.length - (charIndex+1)] = temp;
  
    charIndex++;
  
    return reverseStr(charIndex, arr);
}
My implementation may not be the best way of doing this. I just wanted to find an algorithm for this.
Share

Widgets