Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, May 15, 2007

Java: Convert array of Objects to a List or a Vector


Given an array of objects (not primitives), convert it to a List or a Vector as follows:
// myArray[] is an array of Objects
// Arrays is java.util.Array
List myList = Arrays.asList(myArray);
Vector myVector = new Vector(Arrays.asList(MyArray));

Back to Top



Thursday, April 5, 2007

Java: Sort a 2-dimensional array using Arrays.sort()


While working with a 2-dimensional array (modeled as rows and attributes), one may have to sort the array based on different attributes. However, Arrays.sort(), by default, sorts a 2-dimensional array by its first attribute.

Instead of writing a full-fledged sorting code (mergesort or heapsort, etc.), we can use Arrays.sort() by just redefining its Comparator by specifying the compare() method to sort the array as needed.

You can also change it to return the results in ascending or descending order.
//Using Arrays.sort to sort the array "result[][]", based on the attribute 'd' 
double result[][] = new double[m][n]; // 'm' rows, 'n' attributes
int d=0; // 0 <= d <= n-1
java.util.Arrays.sort(result, new java.util.Comparator() {
public int compare(double[] o1, double[] o2) {
if(o1[d]>o2[d]) return 1; // -1 for descending order
else if(o1[d]<o2[d]) return -1; // 1 for descending order
else return 0;
}
});

Back to Top



Monday, February 26, 2007

Java warning while using clone()


Problem: Using clone() raises warnings
Eg:
Vector v1 = new Vector();
Vector v2 = new Vector();
v1.add("a");
v2 = v1.clone();

Will give the error:
... : incompatible types
found : java.lang.Object
required: java.util.Vector
v2 = v1.clone();
^

Now, casting to generics:
Vector v1 = new Vector();
Vector v2 = new Vector();
v1.add("a");
v2 = (Vector)v1.clone();

But this raises the warning message:
Util.java:252: warning: [unchecked] unchecked cast
found : java.lang.Object
required: java.util.Vector
v2 = (Vector)v1.clone();
^
1 warning

This because clone() returns an Object. But how to use clone() without warnings?

Solution: You can't convert an unqualified type (e.g. Object, Vector) to a
qualified type (e.g. Vector) without warnings.

That's because of type erasure: there is no runtime check that the object is
actually a Vector as (opposed to a simple Vector or Vector) so
the cast is always unsafe and will always result in a warning.

An option would be to NOT use clone() and use your customized function instead. Also, using clone() isn't always recommended by java programmers.

Back to Top


Java warning - Serializable class without serialVersionUID


Problem: warning: [serial] serializable class XXXX has no definition of serialVersionUID

Solution: Two ways to get around this:
1. Add to compiling options: -Xlint:all,-serial (or)
2. Declare serialVersionUID in the code
Eg: public static final long serialVersionUID = 24362462L;
Back to Top


 

Labels