Showing posts with label array/1DArray. Show all posts
Showing posts with label array/1DArray. Show all posts

Tuesday, 17 May 2011

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.

    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