开发者

How to use java.util.Arrays

I'm trying to use the java.util.Arrays class in JavaSE 6 but not sure how i wou开发者_运维问答ld implement it? on an array that I have generated?

before the start of the class i have

import java.util.Arrays


Java Arrays

To declare an array of integers, you start with:

int[] myArray;

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

myArray = new int[10];

To set values in that array, try:

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

Or at instantiation:

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

To get values from the 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, the tutorial from Sun/Oracle will be of great help. You can also check out the Java language specification on Arrays.

Using the Arrays Utility Class

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

So you can do things like 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);


Well 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 this:

// 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 results in

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

C:\Documents and Settings\glow\My Documents>


You have not provided enough information about what you are trying to do. java.util.Arrays only exposes static methods, so you simply pass in your array and whatever other params are necessary for the particular method you are calling. For instance Arrays.fill(myarray,true) would fill a boolean array with the value true.

Here is the javadoc for java.util.Arrays


You can use a static import

import static java.util.Arrays.*;

int[] ints = {3, 4, 1, 2, 5, 7, 6};
sort(ints);


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜