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
  9. Create an ArrayList from another ArrayList. SO
    myObject = new ArrayList<Object>(myTempObject);
  10. Copy an array and convert it to String –
    messageChars = Arrays.copyOf(messageChars, messageChars.length – spaceCount);
    return new String(messageChars);
  11. Removing an element from the arraylist (or any Java collection) while iterating with any undesired affect. SO
    List<String> list = new ArrayList<>();
    
    // This is a clever way to create the iterator and call iterator.hasNext() like
    // you would do in a while-loop. It would be the same as doing:
    //     Iterator<String> iterator = list.iterator();
    //     while (iterator.hasNext()) {
    for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
        String string = iterator.next();
        if (string.isEmpty()) {
            // Remove the current element from the iterator and the list.
            iterator.remove();
        }
    }

 

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