Java/Collections Data Structure/Arrays

Материал из Java эксперт
Версия от 10:26, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

Array Fill Test

   <source lang="java">

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]);
   }
 }

}


 </source>
   
  
 
  



Array Search Test

   <source lang="java">

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;
 }

}


 </source>
   
  
 
  



Compare if two array is equal

   <source lang="java">

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));
 }

}


 </source>
   
  
 
  



Compare two boolean arrays and null

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Compare two byte type arrays

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Compare two char type arrays

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Compare two double type arrays

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Compare two float type arrays

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Compare two int type arrays

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Compare two long type arrays

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Compare two short type arrays

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Comparing Arrays: null arrays are equal

   <source lang="java">

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
 }

}

 </source>
   
  
 
  



Convert an Array to a Vector

   <source lang="java">

/*

* 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());
   }
 }

}


 </source>
   
  
 
  



Convert array of object to array of primitive?

   <source lang="java">


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));
 }

}


 </source>
   
  
 
  



Convert Array to Collection

   <source lang="java">

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) + ", ");
   }
 }

}

 </source>
   
  
 
  



Copy some items of an array into another array

   <source lang="java">


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]);
   }
 }

}

 </source>
   
  
 
  



Demonstrate use of Arrays.sort on Booleans

   <source lang="java">

/*

* 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]);
 }

}


 </source>
   
  
 
  



Expanding an Array

   <source lang="java">

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));
 }

}

 </source>
   
  
 
  



Filling Elements in an Array: boolean type

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Filling Elements in an Array: byte type

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Filling Elements in an Array: char type

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Filling Elements in an Array: double type

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Filling Elements in an Array: float type

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Filling Elements in an Array: int type

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Filling Elements in an Array: long type

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Filling Elements in an Array: short type

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



filling object arrays:

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



fill to a contiguous range of elements in an array: boolean array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Fill to a contiguous range of elements in an array: byte array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Fill to a contiguous range of elements in an array: char array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Fill to a contiguous range of elements in an array: double array

   <source lang="java">


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);
 }

}

 </source>
   
  
 
  



Fill to a contiguous range of elements in an array: float array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Fill to a contiguous range of elements in an array: int array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Fill to a contiguous range of elements in an array: long array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Fill to a contiguous range of elements in an array: short array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Fill to a contiguous range of elements in an array: String array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Finding an Element in a Sorted Array

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



If the element is a primitive type.

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



illustrates how to use some of the methods of the Arrays class:

   <source lang="java">
 

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();
 }

}

 </source>
   
  
 
  



Java Sort byte Array

   <source lang="java">

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);
   }
 }

}

 </source>
   
  
 
  



Java Sort char Array

   <source lang="java">

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);
   }
 }

}

 </source>
   
  
 
  



Java Sort double Array

   <source lang="java">

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);
   } 
 }

}

 </source>
   
  
 
  



Java Sort float Array

   <source lang="java">

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);
   }
 }

}

 </source>
   
  
 
  



Merge (or add) two arrays into one

   <source lang="java">

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));
 }

}

 </source>
   
  
 
  



Shifting Elements in an Array: Shift all elements left by one

   <source lang="java">

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);
 }

}

 </source>
   
  
 
  



Shifting Elements in an Array: Shift all elements right by one

   <source lang="java">

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]

 </source>
   
  
 
  



Shuffle elements of an array

   <source lang="java">


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 + " ");
   }
 }

}


 </source>
   
  
 
  



Sort an array

   <source lang="java">

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]);
 }

}


 </source>
   
  
 
  



Sort an array: case-insensitive

   <source lang="java">

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]

 </source>
   
  
 
  



Sort an array: case-sensitive

   <source lang="java">

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]

 </source>
   
  
 
  



Sorting, Searching, and Inserting into a sorted array

   <source lang="java">

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;
 }

}


 </source>
   
  
 
  



Static methods from Arrays

   <source lang="java">

/* 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.");
   }
 }

}


 </source>
   
  
 
  



Use Arrays.asList() to convert Array to List

   <source lang="java">

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);
   }
 }

}

 </source>
   
  
 
  



use Arrays.copyOf to copy array

   <source lang="java">
 

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();
   }

}

 </source>
   
  
 
  



Use java.util.Arrays.deepToString() to dump the multi-dimensional arrays

   <source lang="java">

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));
 }

}

 </source>
   
  
 
  



When comparing Object arrays, null elements are equal. If the elements are not null, Object.equals() is used.

   <source lang="java">

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 }); 
 }

}

 </source>