I'm new to Java and is learning the concept of array. I have encountered two Java classes: Array and Arrays. I was just wondering what's the difference between the two classes?
-
docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.htmlRahul Tripathi– Rahul Tripathi2016-03-08 06:24:42 +00:00Commented Mar 8, 2016 at 6:24
-
As you might have seen, Array class doesn't have many array manipulation methods. When you create an array, the methods in the array class are called internally by java since you never use the new keyword for creating an array. The Arrays class is basically a utility class which provides more methods for array manipulation.Rahul Sharma– Rahul Sharma2016-03-08 06:27:45 +00:00Commented Mar 8, 2016 at 6:27
3 Answers
They simply serve different purposes with a different set of methods:
java.lang.reflect.Array
The Array class provides static methods to dynamically create and access Java arrays.
This class is essentially a utility class with static methods to manipulate arrays on a lower level. It is usually used for advanced techniques where access to arrays is required through the reflection API.
java.util.Arrays
This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.
This class is essentially a utility class with static methods to work on raw arrays and to provide a bridge from raw arrays to Collection based arrays (List).
For example, you can easily fill an array with a particular value:
import java.util.Arrays;
int[] array = new int[1024];
Arrays.fill(array, 42);
Another useful method is toString which returns a formatted representation of a given array:
System.err.println(Arrays.toString(array));
// [42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, ...]