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

Monday, 16 January 2012

Arrays in Java

Java Array Declaration

Java Array Instantiation
Shorthand method
Java has a shorthand to create an array object and supply initial values at the same time. Here's an example of the syntax at work:

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
Notice that you do not call new when you use this syntax. 

Memory Allocation and initialization
char[] s = new char[10];
for( int i=0; i<26; i++){
    s[i] = (char) ('A' + i);
  }

Array of references can be made similarly:
Point[] p = new Point[26];


No need to pass length of array to function unlike in cpp
To find the number of elements of an array, use array.length. For example,
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);


Iterating over array
Java provides 2 ways of iterating over arrays.
Traditional or old style iteration
for (int i = 0; i < a.length; i++)
    System.out.println(a[i]);


New style

JDK 5.0 introduces a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values.

for (variable : collection)
    statement

sets the given variable to each element of the collection and then executes the statement (which, of course, may be a block). The collection expression must be an array or an object of a class that implements the Iterable interface, such as ArrayList For example,



for (int element : a)
    System.out.println(element);

So here we are taking element from array a and dumping it on output.

Note: println prints each element of the array a on a separate line.

You should read this loop as "for each element in a". The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already contains methods or variables with the same names (such as System.in).

"for each" vs for
The loop variable of the "for each" loop traverses the elements of the array, not the index values.
The "for each" loop is a pleasant improvement over the traditional loop if you need to process all elements in a collection. However, there are still plenty of opportunities to use the traditional for loop. For example, you may not want to traverse the entire collection, or you may need the index value inside the loop.
Jakarta ArrayUtils class: http://jakarta.apache.org/commons/lang/api/index.html

Tuesday, 17 May 2011

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.

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.

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.

    How are arrays stored in java?

    Array in java is on heap, and its reference being on Stack
    (Open your eyes c and cpp programmers)
    A Java array is quite different from a C++ array on the stack. It is, however, essentially the same as a pointer to an array allocated on the heap.

    That is,

    int[] a = new int[100]; // Java


    is not the same as


    int a[100]; // C++


    but rather


    int* a = new int[100]; // C++


    So , take a look at it:


    int[] a = new int[] {100, 99, 98}; // "a" references the array object.
    int[] b; // "b" doesn't reference anything.

    b = a; // Now "b" refers to the SAME array as "a",
    //so its a shallow copy
    b[1] = 0; // Also changes a[1] because a and b refer to the same array.

    Arrays of length 0

    It is legal to have arrays of length 0. Such an array can be useful if you write a method that computes an array result and the result happens to be empty. You construct an array of length 0 as

    new zeroArr[0];

    Note that an array of length 0 is not the same as null.

    Anonymous Arrays in java

    You can even initialize an anonymous array:

    new int[] { 17, 19, 23, 29, 31, 37 }


    This expression allocates a new array and fills it with the values inside the braces. It counts the number of initial values and sets the array size accordingly. You can use this syntax to reinitialize an array without creating a new variable. For example,

    smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };

    is shorthand for

    int[] anonymous = { 17, 19, 23, 29, 31, 37 };
    smallPrimes = anonymous;

    Note Inefficiency. Be careful not to create these anonymous arrays in a loop or as local variables because each use of new will create another array.


    Sunday, 1 May 2011

    equals() method on array

    The equals method is not overloaded for arrays which means that:

    int[]a = new int[]{1};
    int[]b = new int[]{1};
    System.out.println(a.equals(b));


    Output:
    false


    As array is not value based, this was bound to happen. Here equals() method Object class that will be called and we know that this version of equals() method checks for the object references and not the values hence false.

    Monday, 25 October 2010

    2D Array Declaration, Allocation and Initialization

    Introduction

    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.

    Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach.

    Declaration

    Two-dimensional arrays are objects. A variable such as gradeTable is a reference to a 2D array object. The declaration

    int[][] myArray ;

    says that myArray is expected to hold a reference to a 2D array of int. Without any further initialization, 
    it starts out holding null.


    Allocation


    The declaration
    int[][] myArray = new int[3][5] ;

    says that myArray can hold a reference to a 2D array of int, creates an array object of 3 rows and 5 columns, and puts the reference in myArray. All the cells of the array are initialized to zero. The declaration


    int[][] myArray = { 
    {0,0,0,0,0}, 
    {0,0,0,0,0}, 
    {0,0,0,0,0} 
    };



    does exactly the same thing as the previous declaration (and would not ordinarily be used.)

    Initialization


    The declaration


    int[][] myArray = { 
    {8,1,2,2,9}, 
    {1,9,4,0,3}, 
    {0,3,0,0,7} 
    };
    


    creates an array of the same dimensions (same number of rows and columns) as the previous array and initializes the cells to specific values.


    Length of 2D array

    The length of a 2D array is the number of rows it has. You might guess that "length" could be defined as a number pair (rows, columns). But the number of columns may vary from row to row so this will not work.

    eg.
            int arr[][] = new int[2][4];
    
    so arr.length = 2, and arr[0].length=4 i.e. length of row.


    (Note we are using length and not length() )
    Using .length instead of named constants in 2D arrays(unlike c/cpp)

    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";
            }
      

    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 } };
    

    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;
    

    Saturday, 25 September 2010

    Finding an Element in a Sorted Array

    // Create an array with an ordered list of strings
    String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"};

    // Search for the word "cat"
     int index = Arrays.binarySearch(sortedArray, "cat"); // 2

    // Search for a non-existent element
    index = Arrays.binarySearch(sortedArray, "cow"); // -4

    Tuesday, 21 September 2010

    Arrays in java - More

    • Exchanging two elements.
    • .clone()
    • Jakarta ArrayUtils class: http://jakarta.apache.org/commons/lang/api/index.html
    • The array passed to main.
    • Class of arrays?

    Wednesday, 28 July 2010

    Command-Line Parameters in java

    Every Java program has a main method with a String[] args parameter. This parameter indicates that the main method receives an array of strings, namely, the arguments specified on the command line.
    For example, consider this program:

    public class Message
    {
    public static void main(String[] args)
    {
    if (args[0].equals("-h"))
    System.out.print("Hello,");
    else if (args[0].equals("-g"))
    System.out.print("Goodbye,");
    // print the other command-line arguments
    for (int i = 1; i < args.length; i++)
    System.out.print(" " + a[i]);
    System.out.println("!");
    }
    }


    If the program is called as


    java Message -g cruel world

    then the args array has the following contents:

    args[0]: "-g"

    args[1]: "cruel"

    args[2]: "world"

    The program prints the message

    Goodbye, cruel world!

    Differing from cpp
    In the main method of a Java program, the name of the program is not stored in the args array. For example, when you start up a program as



    java Message -h world
    from the command line, then args[0] will be "-h" and not "Message" or "java".
    While in c++ program name is also stored