How to use java.util.Arrays

I am trying to use the java.util.Arrays class in JavaSE 6 but donโ€™t know how to implement this? to the array that I created?

before class i

import java.util.Arrays 
+7
source share
5 answers

Java Arrays

To declare an array of integers, you start with:

 int[] myArray; 

To create an array of ten integers, you can try:

 myArray = new int[10]; 

To set the values โ€‹โ€‹in this array, try:

 myArray[0] = 1; // arrays indices are 0 based in Java 

Or when instantiating:

 int[] myArray2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 

To get values โ€‹โ€‹from an array, try:

 System.out.println(myArray[0]); 

To print all the values โ€‹โ€‹in an array, try:

 // go from 0 to one less than the array length, based on 0 indexing for(int i = 0; i < myArray2.length; i++) { System.out.println(myArray2[i]); } 

For more information, a tutorial from Sun / Oracle will be very helpful. You can also check the Java language specification in arrays .

Using the array utility class

java.util.Arrays contains a bunch of static methods . Static methods are class-specific and do not require an instance of the class to be called. Instead, they are called with the class name as a prefix.

So you can do the following:

 // print a string representation of an array int[] myArray = {1, 2, 3, 4}; System.out.println(Arrays.toString(myArray)); 

or

 // sort a list int[] unsorted = {3, 4, 1, 2, 5, 7, 6}; Arrays.sort(unsorted); 
+16
source

Ok let's say you have an array

 int[] myArray = new int[] { 3, 4, 6, 8, 2, 1, 9}; 

And you want to sort it. You do it:

 // assumes you imported at the top Arrays.sort(myArray); 

Here's the whole shebang:

 import java.util.Arrays; class ArrayTest { public static void main(String[] args) { int[] myArray = new int[] { 3, 4, 6, 8, 2, 1, 9}; Arrays.sort(myArray); System.out.println(Arrays.toString(myArray)); } } 

And that leads to

 C:\Documents and Settings\glow\My Documents>java ArrayTest [1, 2, 3, 4, 6, 8, 9] C:\Documents and Settings\glow\My Documents> 
+8
source

You did not provide enough information about what you are trying to do. java.util.Arrays provides only static methods, so you just pass your array and any other parameters are needed for the specific method that you are calling. For example, Arrays.fill(myarray,true) would populate a Boolean array with true .

Here is the javadoc for java.util.Arrays

+3
source

You can use static import

 import static java.util.Arrays.*; int[] ints = {3, 4, 1, 2, 5, 7, 6}; sort(ints); 
+2
source
 public static void main(String[] args) { double array[] = {1.1,2.3,5.6,7.5, 12.2, 44.7,4.25, 2.12}; Arrays.sort(array,1,3); for(int i =0;i <array.length;i++){ System.out.println(array[i]); } } 

result:

"1.1,2.3,5.6,7.5,12.2,44.7,4.25,2.12"

+1
source

All Articles