Java/Collections Data Structure/Arrays — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:26, 1 июня 2010
Содержание
- 1 Array Fill Test
- 2 Array Search Test
- 3 Compare if two array is equal
- 4 Compare two boolean arrays and null
- 5 Compare two byte type arrays
- 6 Compare two char type arrays
- 7 Compare two double type arrays
- 8 Compare two float type arrays
- 9 Compare two int type arrays
- 10 Compare two long type arrays
- 11 Compare two short type arrays
- 12 Comparing Arrays: null arrays are equal
- 13 Convert an Array to a Vector
- 14 Convert array of object to array of primitive?
- 15 Convert Array to Collection
- 16 Copy some items of an array into another array
- 17 Demonstrate use of Arrays.sort on Booleans
- 18 Expanding an Array
- 19 Filling Elements in an Array: boolean type
- 20 Filling Elements in an Array: byte type
- 21 Filling Elements in an Array: char type
- 22 Filling Elements in an Array: double type
- 23 Filling Elements in an Array: float type
- 24 Filling Elements in an Array: int type
- 25 Filling Elements in an Array: long type
- 26 Filling Elements in an Array: short type
- 27 filling object arrays:
- 28 fill to a contiguous range of elements in an array: boolean array
- 29 Fill to a contiguous range of elements in an array: byte array
- 30 Fill to a contiguous range of elements in an array: char array
- 31 Fill to a contiguous range of elements in an array: double array
- 32 Fill to a contiguous range of elements in an array: float array
- 33 Fill to a contiguous range of elements in an array: int array
- 34 Fill to a contiguous range of elements in an array: long array
- 35 Fill to a contiguous range of elements in an array: short array
- 36 Fill to a contiguous range of elements in an array: String array
- 37 Finding an Element in a Sorted Array
- 38 If the element is a primitive type.
- 39 illustrates how to use some of the methods of the Arrays class:
- 40 Java Sort byte Array
- 41 Java Sort char Array
- 42 Java Sort double Array
- 43 Java Sort float Array
- 44 Merge (or add) two arrays into one
- 45 Shifting Elements in an Array: Shift all elements left by one
- 46 Shifting Elements in an Array: Shift all elements right by one
- 47 Shuffle elements of an array
- 48 Sort an array
- 49 Sort an array: case-insensitive
- 50 Sort an array: case-sensitive
- 51 Sorting, Searching, and Inserting into a sorted array
- 52 Static methods from Arrays
- 53 Use Arrays.asList() to convert Array to List
- 54 use Arrays.copyOf to copy array
- 55 Use java.util.Arrays.deepToString() to dump the multi-dimensional arrays
- 56 When comparing Object arrays, null elements are equal. If the elements are not null, Object.equals() is used.
Array Fill Test
import java.util.*;
public class FillTest {
public static void main(String args[]) {
int array[] = new int[10];
Arrays.fill(array, 100);
for (int i=0, n=array.length; i<n; i++) {
System.out.println(array[i]);
}
System.out.println();
Arrays.fill(array, 3, 6, 50);
for (int i=0, n=array.length; i<n; i++) {
System.out.println(array[i]);
}
byte array2[] = new byte[10];
Arrays.fill(array2, (byte)4);
System.out.println();
Date array3[] = new Date[10];
Date anObject = new Date();
Arrays.fill(array3, "Help");
anObject.setYear(102);
for (int i=0, n=array3.length; i<n; i++) {
System.out.println(array3[i]);
}
}
}
Array Search Test
import java.util.*;
public class SearchTestDemo {
public static void main(String args[]) throws Exception {
int array[] = {2, 5, -2, 6, -3, 8, 0, -7, -9, 4};
// Ensure array sorted
Arrays.sort(array);
printArray("Sorted array", array);
// Search for element in array
int index = Arrays.binarySearch(array, 2);
System.out.println("Found 2 @ " + index);
// Search for element not in array
index = Arrays.binarySearch(array, 1);
System.out.println("Didn"t find 1 @ " + index);
// Insert
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");
// Print out sorted array elements
for (int i=0, n=array.length; i<n; i++) {
if (i != 0) System.out.print(", ");
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[], int element, int index) {
int length = original.length;
int destination[] = new int[length+1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index+1, length-index);
return destination;
}
}
Compare if two array is equal
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] abc = { "a", "b", "c", "d" };
String[] xyz = { "A", "b", "c", "s" };
String[] java = { "Java", "Dot", "Com" };
System.out.println(Arrays.equals(abc, xyz));
System.out.println(Arrays.equals(abc, java));
}
}
Compare two boolean arrays and null
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean[] bArr1 = new boolean[] { true, false };
boolean[] bArr2 = new boolean[] { true, false };
boolean b = Arrays.equals(bArr1, null); // false
b = Arrays.equals(bArr1, bArr2); // true
}
}
Compare two byte type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new byte[] { 0 }, new byte[] { 0 }); // true
}
}
Compare two char type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new char[] { "a" }, new char[] { "a" }); // true
}
}
Compare two double type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new double[] { 0D }, new double[] { 0D }); // true
}
}
Compare two float type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new float[] { 0F }, new float[] { 0F }); // true
}
}
Compare two int type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new int[] { 0 }, new int[] { 0 }); // true
}
}
Compare two long type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new long[] { 0L }, new long[] { 0L }); // true
}
}
Compare two short type arrays
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new short[] { 0 }, new short[] { 0 }); // true
}
}
Comparing Arrays: null arrays are equal
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean[] bArr1 = null;
boolean[] bArr2 = null;
boolean b = Arrays.equals(bArr1, bArr2); // true
}
}
Convert an Array to a Vector
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
/** Convert an Array to a Vector. */
public class ArrayToVector {
public static void main(String[] args) {
Object[] a1d = { "Hello World", new Date(), Calendar.getInstance(), };
// Arrays.asList(Object[]) --> List
List l = Arrays.asList(a1d);
// Vector contstructor takes Collection
// List is a subclass of Collection
Vector v;
v = new Vector(l);
// Or, more simply:
v = new Vector(Arrays.asList(a1d));
// Just to prove that it worked.
Enumeration e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}
}
Convert array of object to array of primitive?
import org.apache.rumons.lang.ArrayUtils;
public class Main {
public static void main(String[] args) {
Integer[] integers = { new Integer(1), new Integer(2), new Integer(3), new Integer(5),
new Integer(8), new Integer(13), new Integer(21), new Integer(34), new Integer(55) };
int[] fibbos = ArrayUtils.toPrimitive(integers);
System.out.println(ArrayUtils.toString(fibbos));
}
}
Convert Array to Collection
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
Integer[] numbers = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };
List list = Arrays.asList(numbers);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + ", ");
}
}
}
Copy some items of an array into another array
public class Main {
public static void main(String[] args) {
String[] letters = { "A", "I", "U", "E", "O" };
String[] results = new String[3];
System.arraycopy(letters, 2, results, 0, 3);
for (int i = 0; i < results.length; i++) {
System.out.println("result = " + results[i]);
}
}
}
Demonstrate use of Arrays.sort on Booleans
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.util.Arrays;
/**
* Demonstrate use of Arrays.sort on Booleans(!). Try it, you"ll get a
* ClassCastException, as there is no ordering of Booleans
*
* @version $Id: SortBooleans.java,v 1.2 2003/06/22 23:19:13 ian Exp $
*/
public class SortBooleans {
public static void main(String[] unused) {
Boolean[] data = { new Boolean(true), new Boolean(false),
new Boolean(false), new Boolean(true), };
Arrays.sort(data); // EXPECT RUNTIME ERROR
for (int i = 0; i < data.length; i++)
System.out.println(data[i]);
}
}
Expanding an Array
import java.lang.reflect.Array;
public class Main {
public static void main(String[] argv) throws Exception {
int[] array = { 1, 2, 3 };
Object newArray = Array.newInstance(array.getClass().getComponentType(),
Array.getLength(array) * 2);
System.arraycopy(array, 0, newArray, 0, Array.getLength(array));
}
}
Filling Elements in an Array: boolean type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean[] booleanArr = new boolean[10];
boolean booleanFillValue = false;
Arrays.fill(booleanArr, booleanFillValue);
}
}
Filling Elements in an Array: byte type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] byteArr = new byte[10];
byte byteFillValue = (byte) 0xFF;
Arrays.fill(byteArr, byteFillValue);
}
}
Filling Elements in an Array: char type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
char[] charArr = new char[10];
char charFillValue = "c";
Arrays.fill(charArr, charFillValue);
}
}
Filling Elements in an Array: double type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
double[] doubleArr = new double[10];
double doubleFillValue = -1;
Arrays.fill(doubleArr, doubleFillValue);
}
}
Filling Elements in an Array: float type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
float[] floatArr = new float[10];
float floatFillValue = -1;
Arrays.fill(floatArr, floatFillValue);
}
}
Filling Elements in an Array: int type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int[] intArr = new int[10];
int intFillValue = -1;
Arrays.fill(intArr, intFillValue);
}
}
Filling Elements in an Array: long type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
long[] longArr = new long[10];
long longFillValue = -1;
Arrays.fill(longArr, longFillValue);
}
}
Filling Elements in an Array: short type
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
short[] shortArr = new short[10];
short shortFillValue = 2;
Arrays.fill(shortArr, shortFillValue);
}
}
filling object arrays:
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
String[] StringArr = new String[1];
String StringFillValue = "";
Arrays.fill(StringArr, StringFillValue);
}
}
fill to a contiguous range of elements in an array: boolean array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
boolean[] booleanArr = new boolean[10];
boolean booleanFillValue = true;
Arrays.fill(booleanArr, startIndex, endIndex, booleanFillValue);
}
}
Fill to a contiguous range of elements in an array: byte array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
byte[] byteArr = new byte[10];
byte byteFillValue = 1;
Arrays.fill(byteArr, startIndex, endIndex, byteFillValue);
}
}
Fill to a contiguous range of elements in an array: char array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
char[] charArr = new char[10];
char charFillValue = 1;
Arrays.fill(charArr, startIndex, endIndex, charFillValue);
}
}
Fill to a contiguous range of elements in an array: double array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
double[] doubleArr = new double[10];
double doubleFillValue = 1;
Arrays.fill(doubleArr, startIndex, endIndex, doubleFillValue);
}
}
Fill to a contiguous range of elements in an array: float array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
float[] floatArr = new float[10];
float floatFillValue = 1;
Arrays.fill(floatArr, startIndex, endIndex, floatFillValue);
}
}
Fill to a contiguous range of elements in an array: int array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
int[] intArr = new int[10];
int intFillValue = 1;
Arrays.fill(intArr, startIndex, endIndex, intFillValue);
}
}
Fill to a contiguous range of elements in an array: long array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
long[] longArr = new long[10];
long longFillValue = 1;
Arrays.fill(longArr, startIndex, endIndex, longFillValue);
}
}
Fill to a contiguous range of elements in an array: short array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
short[] shortArr = new short[10];
short shortFillValue = 1;
Arrays.fill(shortArr, startIndex, endIndex, shortFillValue);
}
}
Fill to a contiguous range of elements in an array: String array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int startIndex = 0;
int endIndex = 4;
String[] stringArr = new String[10];
String stringFillValue = "1";
Arrays.fill(stringArr, startIndex, endIndex, stringFillValue);
}
}
Finding an Element in a Sorted Array
import java.util.Arrays;
public class Main {
public static void main(String[] argv) {
String[] sortedArray = new String[] { "a", "b", "c", "d" };
int index = Arrays.binarySearch(sortedArray, "c");
index = Arrays.binarySearch(sortedArray, "e");
int[] sortedIntArray = new int[] { 1, 2, 3, 5, 7 };
index = Arrays.binarySearch(sortedIntArray, 6);
}
}
If the element is a primitive type.
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
// Create an array with an ordered list of numbers
int[] sortedIntArray = new int[] { 1, 2, 3, 5, 7 };
// Search for 6
int index = Arrays.binarySearch(sortedIntArray, 6);
System.out.println(index);
}
}
illustrates how to use some of the methods of the Arrays class:
import java.util.Arrays;
class ArraysDemo {
public static void main(String args[]) {
int array[] = new int[10];
for (int i = 0; i < 10; i++)
array[i] = -3 * i;
display(array);
Arrays.sort(array);
System.out.print("Sorted: ");
display(array);
// Fill and display the array.
Arrays.fill(array, 2, 6, -1);
System.out.print("After fill(): ");
display(array);
// Sort and display the array.
Arrays.sort(array);
System.out.print("After sorting again: ");
display(array);
// Binary search for -9.
System.out.print("The value -9 is at location ");
int index = Arrays.binarySearch(array, -9);
System.out.println(index);
}
static void display(int array[]) {
for (int i : array)
System.out.print(i + " ");
System.out.println();
}
}
Java Sort byte Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
byte[] b1 = new byte[] { 3, 2, 5, 4, 1 };
for (byte b: b1){
System.out.println(b);
}
Arrays.sort(b1);
for (byte b: b1){
System.out.println(b);
}
byte[] b2 = new byte[] { 5, 2, 3, 1, 4 };
Arrays.sort(b2, 1, 4);
for (byte b: b2){
System.out.println(b);
}
}
}
Java Sort char Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
char[] c1 = new char[] { "c", "h", "a", "r", "s" };
for (char ch: c1){
System.out.print(ch);
}
Arrays.sort(c1);
for (char ch: c1){
System.out.print(ch);
}
char[] c2 = new char[] { "c", "h", "a", "r", "s" };
Arrays.sort(c2, 1, 4);
for (char ch: c1){
System.out.print(ch);
}
}
}
Java Sort double Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
double[] d1 = new double[] { 3.1, 2.1, 5.1, 4.1, 1.1 };
for (double d: d1){
System.out.print(" " +d);
}
Arrays.sort(d1);
for (double d: d1){
System.out.print(" " +d);
}
double[] d2 = new double[] { 5, 2, 3, 1, 4 };
Arrays.sort(d2, 1, 4);
for (double d: d2){
System.out.print(" " +d);
}
}
}
Java Sort float Array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
float[] f1 = new float[] { 3.1f, 2.1f, 5.1f, 4.1f, 1.1f };
for (float f: f1){
System.out.print(" " + f);
}
Arrays.sort(f1);
for (float f: f1){
System.out.print(" " + f);
}
float[] f2 = new float[] { 5.1f, 2.1f, 3.1f, 1.1f, 4.1f };
Arrays.sort(f2, 1, 4);
for (float f: f2){
System.out.print(" " + f);
}
}
}
Merge (or add) two arrays into one
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
String a[] = { "a", "b", "c" };
String b[] = { "d", "e" };
List<String> list = new ArrayList<String>(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
}
}
Shifting Elements in an Array: Shift all elements left by one
public class Main {
public static void main(String[] argv) throws Exception {
int[] array = { 1, 2, 3 };
System.arraycopy(array, 1, array, 0, array.length - 1);
}
}
Shifting Elements in an Array: Shift all elements right by one
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
int[] array = { 1, 2, 3 };
System.arraycopy(array, 0, array, 1, array.length - 1);
System.out.println(Arrays.toString(array));
}
}
//[1, 1, 2]
Shuffle elements of an array
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] alphabets = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
List<String> list = Arrays.asList(alphabets);
Collections.shuffle(list);
for (String alpha : list) {
System.out.print(alpha + " ");
}
}
}
Sort an array
import java.util.Arrays;
public class SortArray {
public static void main(String[] args) {
int[] a = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 100);
}
Arrays.sort(a);
System.out.println("Sorted array!");
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}
Sort an array: case-insensitive
import java.text.Collator;
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String[] myArray = new String[] { "A", "B", "b" };
Arrays.sort(myArray, Collator.getInstance());
System.out.println(Arrays.toString(myArray));
}
}
//[A, b, B]
Sort an array: case-sensitive
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String[] myArray = new String[] { "A", "a", "B" };
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));
}
}
//[A, B, a]
Sorting, Searching, and Inserting into a sorted array
import java.util.Arrays;
public class SearchTest {
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
// Ensure array sorted
Arrays.sort(array);
printArray("Sorted array", array);
// Search for element in array
int index = Arrays.binarySearch(array, 2);
System.out.println("Found 2 at " + index);
// Search for element not in array
index = Arrays.binarySearch(array, 1);
System.out.println("Didn"t find 1 at " + index);
// Insert
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");
for (int i = 0, n = array.length; i < n; i++) {
if (i != 0)
System.out.print(", ");
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[], int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index + 1, length
- index);
return destination;
}
}
Static methods from Arrays
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
(O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly)
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties.
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/
import java.util.Arrays;
import java.util.List;
public class ArraysTester {
private int[] ar;
public ArraysTester(int numValues) {
ar = new int[numValues];
for (int i=0; i < ar.length; i++) {
ar[i] = (1000 - (300 + i));
}
}
public int[] get() {
return ar;
}
public static void main(String[] args) {
ArraysTester tester = new ArraysTester(50);
int[] myArray = tester.get();
// Compare two arrays
int[] myOtherArray = tester.get().clone();
if (Arrays.equals(myArray, myOtherArray)) {
System.out.println("The two arrays are equal!");
} else {
System.out.println("The two arrays are not equal!");
}
// Fill up some values
Arrays.fill(myOtherArray, 2, 10, new Double(Math.PI).intValue());
myArray[30] = 98;
// Print array, as is
System.out.println("Here"s the unsorted array...");
System.out.println(Arrays.toString(myArray));
System.out.println();
// Sort the array
Arrays.sort(myArray);
// print array, sorted
System.out.println("Here"s the sorted array...");
System.out.println(Arrays.toString(myArray));
System.out.println();
// Get the index of a particular value
int index = Arrays.binarySearch(myArray, 98);
System.out.println("98 is located in the array at index " + index);
String[][] ticTacToe = { {"X", "O", "O"},
{"O", "X", "X"},
{"X", "O", "X"}};
System.out.println(Arrays.deepToString(ticTacToe));
String[][] ticTacToe2 = { {"O", "O", "X"},
{"O", "X", "X"},
{"X", "O", "X"}};
String[][] ticTacToe3 = { {"X", "O", "O"},
{"O", "X", "X"},
{"X", "O", "X"}};
if (Arrays.deepEquals(ticTacToe, ticTacToe2)) {
System.out.println("Boards 1 and 2 are equal.");
} else {
System.out.println("Boards 1 and 2 are not equal.");
}
if (Arrays.deepEquals(ticTacToe, ticTacToe3)) {
System.out.println("Boards 1 and 3 are equal.");
} else {
System.out.println("Boards 1 and 3 are not equal.");
}
}
}
Use Arrays.asList() to convert Array to List
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
List<String> list = Arrays.asList("A", "B", "C", "E", "F");
dump(list);
}
public static void dump(List<String> list) {
for (String s : list) {
System.out.println(s);
}
}
}
use Arrays.copyOf to copy array
import java.util.Arrays;
class MainClass
{
public static void main(String args[])
{
int arrayOriginal[] = {42, 55, 21};
int arrayNew[] =
Arrays.copyOf(arrayOriginal, 3);
printIntArray(arrayNew);
}
static void printIntArray(int arrayNew[])
{
for (int i : arrayNew)
{
System.out.print(i);
System.out.print(" ");
}
System.out.println();
}
}
Use java.util.Arrays.deepToString() to dump the multi-dimensional arrays
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String s[] = {"a", "b", "c", "d"};
double d [][]= {
{0.50, 0.20, 0.20, 0.30},
{0.50, 1.10, 0.50, 0.80},
{0.50, 0.70, 0.40},
{0.50, 0.70},
{0.50},
};
System.out.println(Arrays.toString(s));
System.out.println(Arrays.deepToString(d));
}
}
When comparing Object arrays, null elements are equal. If the elements are not null, Object.equals() is used.
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
boolean b = Arrays.equals(new String[] { "a" }, new String[] { "a" });
b = Arrays.equals(new String[] { null }, new String[] { null });
b = Arrays.equals(new String[] { "a" }, new String[] { null });
}
}