Array – Java

Very basic way to use java array –

  1. You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).For primitive types:
    int[] myIntArray = new int[3];
    int[] myIntArray = {1,2,3};
    int[] myIntArray = new int[]{1,2,3};

    For classes, for example String, it’s the same:

    String[] myStringArray = new String[3];
    String[] myStringArray = {"a","b","c"};
    String[] myStringArray = new String[]{"a","b","c"};
  2. Array length –
    myIntArray.length;
  3. Looping an array
    for(int k =0; k <myIntArray.length; k++) {
    System.out.println(a[k]);
    }
    for(int value:myIntArray) {
    System.out.println(value);
    }
  4. Copy an array
    int[] B = Arrays.copyOf(A, j + 1);
    – copy array element from 0 to j+1
  5. ArrayList
    List<Integer> b = new ArrayList<Integer>();
    if (s.contains(value)) {
    continue;
    } else {
    s.add(value);
    }
  6.  // Sort array elements
            Arrays.sort(arr);
  7. Boolean[] vis = new Boolean[n];
    Arrays.fill(vis, false);
  8. If an array or list collection has only primitive type then we can directly print it like-
    System.out.println( list);
    No need to use toString method.
    If we have a list of custom class then we need to override toString method in that class like here

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s