More About Java Arrays

With the addition of Collections in Java, the use of primitives and primitive arrays decreases day by day. But at the API level or framework design level, primitives are highly used even today as they are fast and does’t include method chaining. 

Arrays class in Java, provides the basic to advanced functionality to arrays. Java 6 adds a couple of more functions to this class. They are  
  • copyOf ( T[ ] original, int newLength  )
  • copyOfRange( int[ ] original, int from, int to  ) 
CopyOf copies the array and allows to explicitly defined the size of new array, padding with zeroes (in case of int, float, double, short), null (in case of char) and false (in case of boolean). Its similar to System.arraycopy() but  doesnt allows to specify the size of output array. Simple but useful functionality.
 
Lets understand with the example:-
public class Test {
 public static void main(String[] args) {
  
  int[] orig={1,2,3,4,5,6,6,7,77,8,8};
  int[] copyOf = Arrays.copyOf(orig, 20);
  System.out.println("CopyOf---> "+copyOf.length + "   " +Arrays.toString(copyOf));
  
  int[] copyOfRange= Arrays.copyOfRange(orig, 0, 7);
  System.out.println("CopyOfRange---> "+ copyOfRange.length + "   " +Arrays.toString(copyOfRange));   
 }
}
 Output:-
CopyOf---> 20   [1, 2, 3, 4, 5, 6, 6, 7, 77, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0]
CopyOfRange---> 7   [1, 2, 3, 4, 5, 6, 6]

Keep looking the space for more tips and tricks.

Comments

  1. Hi there,

    Nice blog! Is there an email address I can contact you in private?

    ReplyDelete

Post a Comment

Popular posts from this blog

When to use getClass() and instanceOf in Java

How class.forName loads the Database Driver in JDBC

Why Time gets truncated with ResutSet getDate() function.