Monday, April 22, 2013

Search int in an Array

To search a int in an array, we can use the code:

Arrays.asList(<Array of Integer>).indexOf(<target int>)

Where Arrays.asList(<Array of Integer>) returns a fixed-size list backed by the specified array. indexOf(<target int>) returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Please notice that <Array of Integer> can be Integer[], not int[]; because int is a primitive types, a special data types built into the language; they are not objects created from a class.

Example:

package javatestarray;

import java.util.Arrays;

/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaTestArray {

final static int[] Array_int = {1, 2, 3, 4, 5};
final static Integer[] Array_Integer = {1, 2, 3, 4, 5};

public static void main(String[] args) {

int indexIn_Array_int = Arrays.asList(Array_int).indexOf(3);
System.out.println("indexIn_Array_int = " + indexIn_Array_int);
//not work! -1 will be returned.

int indexIn_Array_Integer = Arrays.asList(Array_Integer).indexOf(3);
System.out.println("indexIn_Array_Integer = " + indexIn_Array_Integer);
//2 will be returned
}
}


No comments:

Post a Comment