Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, March 19, 2009

Interesting Blog by Joshua Bloch

I have been reading an interesting blog by Joshua Bloch, Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken

The following solution can be found in latest version of JDK


int mid = (low + high) >>> 1;


The first thing which comes across my mind is that, (low + high) will cause sign overflow too. However, the comment from the following reader clears out my mind.

">>>" is the unsigned right shift operator. So if I'm not mistaken (low + high) is stored in unsigned int and then shifted one to the right dropping remainder leaving a division by 2 with no remainder returned as a signed int. So it does work.

Very cool, isn't it?

Friday, October 31, 2008

Java Generic Array Creation

Consider the following code :-


class A<E>
{
public A<E>[] array = new A<E>[4];
}


We will get the following compilation error :-

C:\Projects\Main\src\test\Main.java:24: generic array creation


This is due to erasure in generic http://en.wikipedia.org/wiki/Generics_in_Java, which posts a limit to generic array creation.

The workaround is simple. Here is the fixed code :-


class A<E>
{
@SuppressWarnings("unchecked")
public A<E>[] array = new A[4];
}


However, is it safe to do so? Yes. Generics are checked at compile-time for type correctness. We still able to receive "protection" from the above code. Consider the following :-


public class Main {
public static void main(String[] args) {
A<String> a = new A<String>();
// We try to do some stupid thing here.
a.array[0] = 0;
}
}


The compiler will prevent us to do "stupid" thing by flagging us :-

C:\Projects\Main\src\test\Main.java:32: incompatible types


We are being protected :)

Followers