Tuesday, March 29, 2016

Java, how to onvert primitive array type to Boxed type, convert int array to Integer array

With Java 8's functional interfaces, one could be more concise and use shorter codes to convert a primitive array to the corresponding boxed type. Below we will use int array and Integer array as an example.

Prior to Java 8, we could use a few ways below to copy from the primitive array to a new array of the same length but of the boxed type:


int[] old = {1,2,3,4,5};
Integer[] newArray = new Integer[old.length];
int i = 0;
for (int value : oldArray) {
    newArray[i++] = Integer.valueOf(value);
}

// or Arrays.copyOf()

System.arraycopy(old, 0, newArray, 0, old.length);


With java 8, we could use the stream interface and lambda expressions as below.

int[] old = {1,2,3,4,5};
Integer[] newArray = IntStream.of(old).boxed()
                     .toArray(Integer[]::new);

// or

newArray = Arrays.stream(old).boxed()
                 .toArray(Integer[]::new);

Alternatively, for ease of printing the array out, one could also collect it to a list after the stream operations.

int[] old = {1,2,3,4,5};

List<integer> newArrayList = IntStream.of(old).boxed()
                        .collect(Collectors.toList());
System.out.println(newArrayList);

The output will be:

[1, 2, 3, 4, 5]

Sunday, March 27, 2016

String Search Algorithm - Brute Force

Denote that the goal is to find the first index of String needle with a length of M in String haystack with a length of N. Typically, M << N.

The brute force algorithm is to align needle at index i of haystack and compare the two, if not match, move up index i till i = N - M. Return - 1 if not found. The algorithm has a worst case running time of M*N, in practice typical time is ~ 1.1 N.

A java implementation is below:




public int strStrBF(String haystack, String needle) {
	for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
		int j = 0;
		for (; j < needle.length(); j++) {
			if (haystack.charAt(i + j) != needle.charAt(j)) break;
		}
		if (j == needle.length()) return i;
	}
	return -1;
}

Sunday, March 20, 2016

Eclispe Source Hover Background

After using the dark theme in eclipse and switched back, one background did not change back to white/grey color. That is when mouse over / hovering on the folded source code, the background is still black. To change this, use Window - Preferences - Java - Editor - Source Hover Background, change it to system default, or pick a color you like, or restore defaults.


Friday, March 18, 2016

Syntax Highlighting on blogger.com blogspot.com

To add syntax highlighting feature for your blogger.com blog, you can use Alex Gorbatchev's javascripts.

Go to your blog dashboard, settings, template, edit html. Add the html codes below inside the head section of the template.



    
    

You can switch to a different theme or add more programming languages supported. To use the feature, wrap your code with <pre class="brush:java"> </pre>  or <script class="brush:java"> </script> tags. See Alex's website for pros and cons of each method.

Thursday, March 17, 2016

Using Java's Reflection for Testing

Repeatedly writing for loops for testing is not fun.

We can use Java reflection API (java.lang.reflect package) to maximize code reuse and help testing.

private final static String SUCCESS = "Congrats! All tests passed.";

public static <T, R> void assertEqual(String className, String methodName,
  T[] inputs, R[] expected) {
  // make sure they have same length
  validateLengths(inputs, expected);
  
  try {
    // use reflection to get type of class indicated by "className"
    Class<?> c = Class.forName(className);
    Class<T> inputType = (Class<T>) inputs[0].getClass();
    Method m = c.getMethod(methodName, inputType);

    // static methods will ignore this instance
    Object o = c.newInstance();

    for (int i = 0; i < inputs.length; i++) {
      R e = expected[i];
      R output = (R) m.invoke(o, inputs[i]);

      // has to test deep equal for array type
      if (e.getClass().isArray()) {
        int n = Array.getLength(e);
        for (int j = 0; j < n; j++) {
          if (!Array.get(e, j).equals(Array.get(output, j))) {
            System.out.println("test failed for "
              + Arrays.asList(inputs[i]) + " expected "
              + Arrays.asList(e) + ", output "
              + Arrays.asList(output));
            System.exit(-1);
          }
        }
      } else if (!e.equals(output)) {
        System.out.println("test:\n " + inputs[i] + "failed, "
          + " expected " + expected + ", output " + output);
        System.exit(-1);
      }

    }
    
    // all tests passed
    System.out.println(SUCCESS);
  
  } catch (ClassNotFoundException | IllegalAccessException
    | IllegalArgumentException | InvocationTargetException
    | NoSuchMethodException | SecurityException
    | InstantiationException e) {
    //handle your exceptions here
    e.printStackTrace();
  }
}




To use the method, call:

assertEqual("my.pkg.className","methodName",inputArray,
         expectedResultsArray);



Don't forget to include the package name.