Showing posts with label Arrays. Show all posts
Showing posts with label Arrays. Show all posts

Friday, July 15, 2011

Stringifying Java Arrays

J2SE 5 provided significant new language features that made Java significantly easier to use and more expressive than it had ever been. Although "big" new J2SE 5 features such as enums, generics, and annotations, there was a plethora of new APIs and methods that have made our lives easier ever since. In this post, I briefly look at two of my favorites when dealing with Java arrays: the Arrays.toString(Object[]) method and the Arrays.deepToString(Object[]) method.

The Arrays class has been around since JDK 1.2, but the methods for conveniently and simply converting arrays to a readable String including relevant array content without using Arrays.asList() were added with J2SE 5. Both Arrays.toString(Object[]) and Arrays.deepToString(Object[]) are static methods that act upon the arrays provided to them. The former, Arrays.toString(Object[]), is intended for single-dimension arrays while the latter, Arrays.deepToString(Object[]), is intended for multi-dimensional arrays. As my example later in this post will demonstrate, the multi-dimension deepToString will produce expected results even for single-dimension arrays. The two methods also provide easy and safe null handling, something that I appreciate.

The next code listing is for a simple demonstration class that demonstrates trying to put the contents of various types of Java arrays into a String format. The types of arrays demonstrated are a single dimension array, a double dimensional array representing multi-dimensional arrays of various sizes, and an array that is really just null. The three methods demonstrated for getting a String out of these three types of arrays are (1) simple Object.toString() on each array (implicitly in case of null array to avoid the dreaded NullPointerException), (2) Arrays.toString(Object[]), and (3) Arrays.deepToString(Object[]).
package com.vaani.arraytest;

import java.util.Arrays;
import static java.lang.System.out;

/**
* Simple demonstration of Arrays.toString(Object[]) method and the
* Arrays.deepToString(Object[]) method.
*/
public class Array2String
{
/**
* Demonstrate usage and behavior of Arrays.toString(Object[]).
*/
private static void demonstrateArraysToString()
{
out.println(
"Single Dimension Arrays.toString: "
+ Arrays.toString(prepareSingleDimensionArray()));
out.println(
"Double Dimension Arrays.toString: "
+ Arrays.toString(prepareDoubleDimensionArray()));
out.println(
"Null Array Arrays.toString: "
+ Arrays.toString(prepareNullArray()));
}

/**
* Demonstrate usage and behavior of Arrays.deepToString(Object[]).
*/
private static void demonstrateArraysDeepToString()
{
out.println(
"Single Dimension Arrays.deepToString: "
+ Arrays.deepToString(prepareSingleDimensionArray()));
out.println(
"Double Dimension Arrays.deepToString: "
+ Arrays.deepToString(prepareDoubleDimensionArray()));
out.println(
"Null Array Arrays.deepToString: "
+ Arrays.deepToString(prepareNullArray()));
}

/**
* Demonstrate attempting to get String version of array with simple toString()
* call (not using Arrays class).
*/
private static void demonstrateDirectArrayString()
{
out.println("Single Dimension toString(): " + prepareSingleDimensionArray().toString());
out.println("Double Dimension toString(): " + prepareDoubleDimensionArray());
out.println("Null Array toString(): " + prepareNullArray());
}

/**
* Prepare a single-dimensional array to be used in demonstrations.
*
* @return Single-dimensional array.
*/
private static Object[] prepareSingleDimensionArray()
{
final String[] names = {"Aaron", "Bianca", "Charles", "Denise", "Elmer"};
return names;
}

/**
* Prepare a double-dimension array to be used in demonstrations.
*
* @return Double-dimensional array.
*/
private static Object[] prepareDoubleDimensionArray()
{
final Object[][] namesAndAges = {
{"Aaron", 10}, {"Bianca", 25}, {"Charles", 32}, {"Denise", 29}, {"Elmer", 67}};
return namesAndAges;
}

/**
* Prepare a null array.
*
* @return Array that is really null.
*/
private static Object[] prepareNullArray()
{
return null;
}

/**
* Main executable function for demonstrating Arrays.toString(Object[]) and
* Arrays.deepToString(Object[]) methods.
*/
public static void main(final String[] arguments)
{
out.println("\n\n\nDemonstrating direct array to string using toString():");
demonstrateDirectArrayString();

out.println("\n\n\nDemonstrating Arrays.toString() to get arrays as String:");
demonstrateArraysToString();

out.println("\n\n\nDemonstrating Arrays.deepToString() to get the String:");
demonstrateArraysDeepToString();
}
}


The above code exercises the three mentioned approaches for getting a String out of an array on the three different types of arrays: single dimension, multi dimension, and null array. The output from running this code demonstrates the utility of the different approaches. That output is shown next.

Demonstrating direct array to string using toString():
Single Dimension toString(): [Ljava.lang.String;@3e25a5
Double Dimension toString(): [[Ljava.lang.Object;@19821f
Null Array toString(): null
///////////
Demonstrating Arrays.toString() to get arrays as String:
Single Dimension Arrays.toString: [Aaron, Bianca, Charles, Denise, Elmer]
Double Dimension Arrays.toString: [[Ljava.lang.Object;@addbf1, [Ljava.lang.Object;@42e816, [Ljava.lang.Object;@9304b1, [Ljava.lang.Object;@190d11, [Ljava.lang.Object;@a90653]
Null Array Arrays.toString: null


///////////
Demonstrating Arrays.deepToString() to get the String:
Single Dimension Arrays.deepToString: [Aaron, Bianca, Charles, Denise, Elmer]
Double Dimension Arrays.deepToString: [[Aaron, 10], [Bianca, 25], [Charles, 32], [Denise, 29], [Elmer, 67]]
Null Array Arrays.deepToString: null

The code above and its corresponding output lead to several observations:



  1. Simple Object.toString() on arrays is seldom what we want as it only prints the String representation of the array itself and not of its contents.
  2. Arrays.toString(Object[]) will print a String representation for multi-dimensional arrays, but this representation suffers the same drawbacks as Object.toString() after the first dimension. The first dimension (and only dimension for a single dimension array) gets put into an expected String, but deeper dimensions have the same Object.toString() treatment.
  3. Arrays.deepToString(Object[]), while intended for multi-dimensional arrays, produces the expected results for both single and multi-dimensional arrays.
  4. Both Arrays.toString(Object[]) and Arrays.deepToString(Object[]) handle null array gracefully, simply returning a String "null".

I tend to use Java Collections far more than I use Java arrays. However, when I do need to work with arrays, it is nice to have the many useful features of the java.util.Arrays class. As this post has demonstrated, Arrays.toString(Object[]) and Arrays.deepToString(Object[]) are particularly valuable in obtaining a useful String representation of an array's contents. The java.util.Arrays class provides similar "deep" methods for performing equals and hashCode functionality on multi-dimensional arrays: Arrays.deepEquals and Arrays.deepHashCode.

Friday, July 1, 2011

Parametrized types and Arrays : Covariance of Arrays

Array types are covariant,  if a type A is a subtype of type B, then A[] is a subtype of B[].

However we have just seen that the parameterised types are not covariant. This leads to an anomaly that cannot be resolved, so Java has the rule that arrays of parameterised types are not allowed. Otherwise we could write code that would potentially cause a ClassCastException, and the whole idea behind the generic types is to remove this possibility so long as no compiler warnings are issued.

Places where covariance of arrays may be harmful:
Case 1 : ArrayStoreException
Apple[] apples = new Apple[1];
Fruit[] fruits = apples;
fruits[0] = new Strawberry();//generates ArrayStoreException

The code indeed compiles, but the error will be raised at runtime as an ArrayStoreException. Because of this behavior of arrays, during a store operation, the Java runtime needs to check that the types are compatible. The check, obviously, also adds a performance penalty that you should be aware of.


Case 2: ClassCastException
List<String>[] wordlists = new ArrayList<String>[10];
ArrayList<Integer> ali = new ArrayList<Integer>();
ali.add( new Integer(123) );
Object[] objs = wordlists;
objs[0] = ali; // No ArrayStoreException
String s = wordlists[0].get(0); // ClassCastException

Once more, generics are safer to use and "correct" this type safety weakness of Java arrays.

In the case you're now wondering why the subtyping relation for arrays is covariant, I'll give you the answer that Java Generics and Collections give: if it was invariant, there would be no way of passing a reference to an array of objects of an unknown type (without copying every time to an Object[]) to a method such as:

void sort(Object[] o);

With the advent of generics, this characteristics of arrays is no longer necessary (as we'll see in the next part of this post) and should indeed by avoided.

Friday, June 24, 2011

Converting a Collection to an array

If you have been using Collections in Java 5 you probably have stumbled upon a problem of converting a given Collection<T> into an array of type T. In the Collection interface, there is a method called toArray() which returns an array of type Object[]. But then, if since Java 5 Collections are using generics, shouldn’t it be possible to get an array T[] of the generic type we used in the declaration of our Collection<T>? Well, there is a method T[] toArray(T[] a). But what is that strange “T[] a” doing there? Why is there no simple method T[] toArray() without any strange parameters? It seams like it shouldn’t be a big problem to implement such a method… but actually it is not possible to do so in Java 5, and we will show here why.
Let’s start from trying to implement that method by ourselves. As an example, we will extend the ArrayList class and implement there a method T[] toArrayT(). The method simply uses the standard Object[] toArray() method and casts the result to T[].

import java.util.*;

/**
 * Implementation of the List interface with "T[] toArrayT()" method.
 * In a normal situation you should never extend ArrayList like this !
 * We are doing it here only for the sake of simplicity.
 * @param <T> Type of stored data
 */
class HasToArrayT<T> extends ArrayList<T> {
    public T[] toArrayT() {
        return (T[]) toArray();
    }
}

public class Main {
    public static void main(String[] args) {
        // We create an instance of our class and add an Integer
        HasToArrayT<Integer> list = new HasToArrayT<Integer>();
        list.add(new Integer(4));

        // We have no problems using the Object[] toArray method
        Object[] array = list.toArray();
        System.out.println(array[0]);

        // Here we try to use our new method... but fail on runtime
        Integer[] arrayT = list.toArrayT(); // Exception is thrown :
        // "Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer"
        System.out.println(arrayT[0]);
    }
}

If you compile it and run, it will throw an exception when trying to use our new method. But why? Didn’t we do everything right? Objects stored in the array ARE Integers and toArray method returns an array of those objects, so what is the problem?

Java compiler gives us a hint to understand what is wrong. During compilation, you should see a warning at line 12, saying something like “Type safety: Unchecked cast from Object[] to T[]“. Let’s follow this trace and check if the array that comes out of our toArrayT method is really of type Integer[]. Put this code somewhere in main() method before the Integer[] arrayT = list.toArrayT() line :

System.out.println("toArrayT() returns Integer[] : "
    + (list.toArrayT() instanceof Integer[]));

When you run the program, you should get “false”, which means that toArrayT() DID NOT return Integer[]. Why? Well, many of you probably know the answer – it is Type Erasure. Basically, during compilation the compiler removes every information about the generic types. Effectively, when the program runs, all the appearances of T in our HasToArrayT class are nothing more than simple Object’s. It means, that the cast in the function toArrayT does not cast to Integer[] any more, even if we are using Integer in the declaration of the generic type. Actually, there is also a second problem here, coming from the way Java handles casting of arrays. This time however we would like to concentrate just on the first one – usage of generics.
So, if the information that T is an Integer is no longer there at runtime, is there any way to really return an array of type Integer[] ? Yes, there is, and it is exactly what the method T[] toArray(T[] a) in the Collections framework is doing. But the price you have to pay for it is the additional argument a, whose instance you have to create first by yourself. How do they use it there? Let’s look at how it is really implemented in, for example, ArrayList :

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        // Make a new array of a's runtime type, but my contents:
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

As it is explained in the method’s Javadoc, if the specified array a is big enough it just copies elements into this array. If not, it creates a new array. What is important for us, is that when creating a new array it uses Arrays.copyOf method, specifying there a.getClass() as the type of array to create. So that’s where it needs that additional argument – to know what type of array to create. But then you might say, would it not be easier to fit there T.class instead of a.getClass()? No. Because of type erasure, T is no longer the type we specified. Moreover, we would get a compile time error if we wrote T.class! Some of you may be thinking about creating a new array the simple way – new T[], but it is also not possible because of the same reason. We have already discussed how to get Generic Arrays in Java here.
To put it straight, in order to return a new array of T, the type that we really specified, we MUST give something of that type to the function toArray. There is no other way the function could now what type of array it should create, because the generic type T supplied when creating that Collection is erased every time during compilation.
One other way to implement such a method is by using the Class<T[]> type as an input parameter. This way, instead of having to create a new instance a of array T[] and then using it in the function toArray(a), we could use the .class field – toArrayT(TYPE[].class) :

public T[] toArrayT(Class<T[]> c) {
        return (T[]) Arrays.copyOf(toArray(), size(), c);
 }

It still takes an argument, but it has two advantages over the T[] toArray(T[] a) function. First, it does not require you to create an instance of an array just to pass it to the function. Second, it is simpler. Of course, it has still the disadvantage of having to pass some argument.

After all, there is no perfect way to perform such a conversion. The best solution would be not to use arrays at all. Code with arrays is difficult to maintain and invites people to make mistakes that often come out not earlier than on runtime. Using collections is generally much preferred and if you use them all the time, you will not be forced to deal with the toArray method.

Monday, June 20, 2011

Array iteration optimization in Java

The problem
I am working on a project right now which involves lots of loops that look like:

for( int x = 0; x < size; x++ ) {
    for( int y = 0; y < size; y++ ) {
        for( int z = 0; z < height; z++ ) {
            if( somearray[x][y][z] == somevalue) {
                // do something
            }
        }
    }
}

Writing out these loops by hand got tedious, error-prone, high-maintenance, and makes the code longer.
If I was writing in C++, I could macro it out.
In Java, for reasons I tend to agree with, there are no macros, not an option. Same deal in C#, as far as I know.
Idea One: anonymous classes
My first idea was to write a class which would use an anonymous class to call back into my code. I figured one could use it like this:
new Iterator(startVector3i, endVector3i).iterate( new Callback(){
   public void callback(Vector3i next ){
      // do stuff here
   }
));

Technically this is possible, except the code inside has no access to our local variables in our calling method, which makes it not terribly useful I feel.

Discovery: using an iterator class surprisingly slow

Next, I made an iterator class that worked like this:
ArrayIterator iterator = new ArrayIterator(startVector3i,endVector3i);
while( iterator.next() ){
    if( somearray[iterator.x][iterator.y][iterator.z] == somevalue ) {
        // do something
    }
}

This took a long time to execute. Compared to the bog-standard nested for-loops we started with, it took 20 times longer to execute!

Why?

Deduction: java optimizes processor cache requests in nested for loops

It baffled me why this approach was so slow. Surely a method call is not so expensive?

I tried all sorts of different performance tests, and in the end found the following very specific code sample:

for( int x = 0; x < size; x++ ) {
    for( int y = 0; y < size; y++ ) {
        for( int z = 0; z < height; z++ ) {
            if( somearray[x][y][z] == somevalue) {
                // do something

This runs quickly.

for( int x = 0; x < size; x++ ) {
    for( int y = 0; y < size; y++ ) {
        for( int z = 0; z < height; z++ ) {
            if( wrapperObject.getArrayValueAt(x,y,z) == somevalue) {
                // do something
This runs 20 times slower, even though normal simple method calls were not particularly expensive I found.
My conclusion is that when we iterate over an array with an obvious in-lined for loop, java/jvm/processor has enough information available to realize it can optimize by fetching a batch of values from the array all at once.
When the array access is not directly inside the nested for loop, this doesn’t work.
So, my conclusion is that it seems any iterative access to large arrays needs to be explicitly inlined with the iterating loop in the code.
Edit: found a relevant sun wiki page that I think explains this effect
http://wikis.sun.com/display/HotSpotInternals/RangeCheckElimination
Basically, a bunch of range checks are carried out on array access, and when the access is done in a for loop, many of these checks are eliminated, where the loop body is inlined.

Wednesday, June 15, 2011

How to create and initialize generic array in java ?

I recently required generic array in my project. But in java, to initialize array generically is a problem, because the way generics are implemented.

So for eg. you can't do this :
public class GenericArray<E> {
    private E a[];
    public GenericArray()
    {
        a = new E[INITIAL_ARRAY_LENGTH];
    }
}

Solution 
But still I googled and found some solutions.
Solution 1 : Use reflections
So one solution to this using reflection, and making an array at runtime and point the reference to some new array.
class GenericArray<T> {
  public GenericArray(Class<T> clazz,int capacity) { 
//Create array at runtime using reflections 
array=(T[])Array.newInstance(clazz,INITIAL_ARRAY_LENGTH);
  }

  private final T[] array;
}

Solution 2 : Use Object[] and cast to E
2nd solution is to use Object Class to solve the problem :

E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];

Or if you need value to be returned from the array at particular index try this :

public class GenericArray<E>{
private Object[] a;


public GenSet(int s) {
    a = new Object[s];
}


@SuppressWarnings({"unchecked"})
E get(int i) {
    return (E) a[i];
}
}

This solved what I needed, but not in a clean way. But if thing works, it good for us. :)


Thursday, May 19, 2011

When to use arrays and when arraylist?

Programmers are frequently faced with the choice of using a simple array or an ArrayList. If the data has a known number of elements or small fixed size upper bound, or where efficiency in using primitive types is important, arrays are often the best choice. However, many data storage problems are not that simple, and ArrayList (or one of the other Collections classes) might be the right choice.

Wednesday, May 18, 2011

Array Operations on collections in java

The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. They allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array. For example, suppose c is a Collection The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c:
Object[] a = c.toArray();
Suppose c is known to contain only strings. The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c:

String[] a = (String[]) c.toArray(new String[0]);

Assigning 1D array to row of 2D array

int myArray[][] = new int [4][4];
myArray[0] = new int[] {1, 9, 4,7,8} ;
int[] x = {1, 7, 4,5,6,7,6,90,4,5,6,7,8,9,0,1,3,4,5} ; // declare and init x
myArray[1]=x;

Visualizing 2D arrays : How java implements multidimensional arrays ?

A two dimensional array is implemented as an array of one dimensional arrays. This is called "array of arrays" approach.

2-dimensional arrays are usually represented with a row-column "spreadsheet" style. Assume we have an array, a, with two rows and four columns.

int[][] a = new int[2][4];  // Two rows and four columns.


















a[0][0]a[0][1]a[0][2]a[0][3]
a[1][0]a[1][1]a[1][2]a[1][3]
Two-dimensional arrays are usually visualized as a matrix, with rows and columns. This diagram shows the array a with its corresponding subscripts.

This actually allocates 3 objects: a one-dimensional array of 2 elements to hold each of the actual row arrays, and a two one-dimensional arrays of 4 elements to represent the contents of the rows.


Common approach to implement multidimensional arrays


There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Some languages, like Java, build multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. C++ supports both styles.

Types of 2D arrays in java

2D arrays in java are of 2 types – even and ragged or uneven arrays.

Defining an even array

Here, Each row of a 2D array may have a same number of cells in the array.

int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];


Defining non-uniform or ragged arrays


Here, each row of a 2D array may have a different number of cells.


int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];


Similarly we can initialized ragged arrays like :


int[][] uneven = 
{ { 1, 9, 4 },
{ 0, 2},
{ 0, 1, 2, 3, 4 } };

Common usage of ragged arrays

One consequence of arrays of arrays is that each row can be a different size, called ragged or non-uniform arrays.

One usage of ragged arrays is triangular arrays. For example, we could create a lower triangular array, allocating each row "by hand" as follows. Note how new can be used with only the row dimension.

int[][] tri;

//... Allocate each part of the two-dimensional array individually.
tri = new int[10][]; // Allocate array of rows
for (int r=0; r < tri.length; r++) {
tri[r] = new int[r+1]; // Allocate a row
}


A good example of a triangular array is one of those tables of the distance between two cities that is often in the front of some road atlas covers. The distance from New Delhi to Agra is the same as the distance from Agra to New Delhi- there's not need to have it twice in the same table - at least if you have a need for that remaining space.

Using .length instead of named constants in 2D arrays

Named constants make a program very readable, but they may not be available if the array has been passed as a parameter. You can get the size of each dimension with the .length attribute. This is the most general style.

for (int row = 0; row < a2.length; row++) {
for (int col = 0; col < a2[row].length; col++) {
output += " " + a2[row][col];
}
output += "\n";
}

Iterating over 2 Dimensional Arrays

Iterating down rows, then across columns is often better. The most common practice is for the outer loop be for the row and the inner loop for the column. If your program requires the outer iteration by columns, that's fine, but the default row-first iteration gives the best performance because "locality of reference" improves the perfomance of cache and virtual memory. It also allows use of the handy foreach loop.

int[][] a2 = new int[ROWS][COLS];

String output = ""; // Accumulate text here (should be StringBuilder).
//... Print array in rectangular form using nested for loops.
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
output += " " + a2[row][col];
}
output += "\n";
}


foreach style for loop


for (int[] row : a2) {
for (int val : row) {
output += " " + val;
}
output += "\n";
}

Naming convention : Use named constants for array sizes

It's useful to define constants for the number of rows and columns. The reason named constants can better code is that these numbers may represent part of the problem domain and they will be used in other parts of the code. If a change is every necessary (eg, the number of teams in the Big Ten), changing one named constant will change all parts of the program. Each numeric "constant" should only appear once (the "DRY" principle).

static final int ROWS = 2;
static final int COLS = 3;
. . .
int[][] board = new int[ROWS][COLS];

Many row and column indexes (indices is the traditional English plural, but many prefer the more modern indexes) have a meaning, and aren't just simply arbitrary numbers. The following example might be used to represent the number of accidents on by day of the month and the hour of the day. See programming problems below for some examples using this array.
static final int DAYS  = 31;
static final int HOURS = 24;
. . .
int[][] accidents = new int[DAYS][HOURS];

Multi-dimensional arrays in java

Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ... In practice most arrays are one-dimensional, and two-dimensional (rows and columns) are also quite common. Higher dimensional arrays are less common so they aren't used in the examples, but there's nothing mysterious about them and the same principles apply.
Two-dimensional arrays are used whenever the model data is best represented with rows and columns, or has two varying aspects (eg, gender and age, weight and height, ...). It's also the idea, altho not the implementation, of graphics that specifies a two (or three) dimensional position with an x and y (and z) coordinate.
Terminology. Other terms you will see for a two-dimensional array are matrix or table.

Equals method of Arrays in java

Java have equals method as static method in java.util.Arrays class. But you can also have equals on the reference of the array in java.

equals static method in Arrays

static boolean equals(type[] a, type[] b)

returns TRue if the arrays have the same length, and if the elements in corresponding indexes match.

equals method on reference of array

See here to get more on this.

Sorting an array in java

For sorting Arrays.sort(arr) is used, which is static function in arrays class.

Here a is array and method uses a tuned version of the QuickSort algorithm

int arr[] = {4,3,1};
Arrays.sort(arr);



This will sort the array in ascending order.


Seeing various sorting methods:


 

























Method
Arrays sort methods


Description


Arrays.sort(pa);

 


Sorts the elements of the array of a primitive type into ascending order using their natural ordering.


Arrays.sort(pa, from, to);


Sorts the elements pa[from]...pa[to-1] of a primitive type. into ascending order.


Arrays.sort(oa);


Sorts the elements of the array of an object type into ascending order, using the order defined by Comparable interface, which defines the compareTo method. Note that many Java classes such as String (but not StringBuffer), Double, BigInteger, etc implement Comparable.


Arrays.sort(oa, from, to);


Sorts the elements of the array, in the range from...to of an object type into ascending order.


Arrays.sort(oa, comp);


Sorts the elements of the array of an object type into ascending order, using the Comparator comp.


Arrays.sort(oa, from, to, comp);


Sorts the elements of the array, in the range from...to of an object type into ascending order using the Comparator comp.

Copying arrays in java

  • ArrayCopy
    System.arraycopy(from, fromIndex, to, toIndex, count);

    eg. System.arraycopy(arr1, 2, arr2, 3, 4);
    The shallowcopy starts at position 2 in the source array i.e. arr1 and copies four entries, starting at position 3 of the target array i.e. arr
  • CopyOf

    arr2 = Arrays.copyOf(a, newLength);

    New shallow copy of array with new length. If longer, uses default values.
  • copyOfRange

    arr2 = Arrays.copyOfRange(a, from, to);

    New shallow copy of portion of array.
  • Arrays and exceptions in java

    Some common array programming mistakes are:
    Runtime error: Forgetting that array subscripts start with zero. OR Going out of bound
    Compile-time error: Writing a.length() instead of a.length. The length() method is used with Strings, not arrays.
    Compile-time error: Declaring an array with a size. Eg, int[100] a; instead of int[] a = new int[100];.

    Managing the subscript in java

    In Java, the [] operator is predefined to perform bounds checking. Furthermore, there is no pointer arithmetic—you can't increment a to point to the next element in the array.Java always checks subscript legality to be sure the subscript is >= 0, and less than the number of elements in the array. If the subscript is outside this range, Java throws ArrayIndexOutOfBoundsException. This is far superior to the behaver of C and C++, which allow out of range references. Consequently, Java programs are far less susceptible to bugs and security flaws than C/C++ programs.

    Chitika