Java/Collections Data Structure/Array
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Array 2D
- 2 Array Copy Demo
- 3 Array Hunt game
- 4 Array initialization
- 5 Array Initializers
- 6 ArrayListDemo done over using an ArrayList
- 7 Array Of Arrays Demo 2
- 8 Arrays of primitives
- 9 Can you change the .length of an array
- 10 Clone Array
- 11 Convert array of primitives into array of objects
- 12 Copy an array
- 13 Copying Elements from One Array to Another
- 14 Create a repeated sequence of character
- 15 Create multidimension arrays
- 16 Creating an array of nonprimitive objects
- 17 Creating arrays with new
- 18 Creating a Two-Dimensional Array
- 19 Define array for class
- 20 Doubling the size of an array
- 21 Dump array content: Convert the array to a List and then convert to String
- 22 Dump multi-dimensional arrays
- 23 Extend the size of an array
- 24 Get array upperbound
- 25 Grow array
- 26 Initialization and re-assignment of arrays
- 27 Initialize a static array
- 28 Initialize multidimensional array
- 29 Initializing Array Values
- 30 Initializing a Two Dimensional Array
- 31 Java program to demonstrate multidimensional arrays
- 32 java.utils.Arrays provides ways to dump the content of an array.
- 33 Multi Dimension Array
- 34 Multiply two matrices
- 35 Reinitializes a byte array
- 36 Reinitializes an int array
- 37 Resize an array, System.arraycopy()
- 38 Reverse array elements order
- 39 Show Two-Dimensional Array of Objects
- 40 String array and output to console
- 41 Sum all elements in the array
- 42 Timing array loop performance
- 43 To get the number of dimensions
- 44 Triangular array
- 45 Use the new shorthand notation to iterate through an array
- 46 Using the length Variable
Array 2D
/*
* 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.
*/
public class Array2D {
public static void main(String[] args) {
int[][] data;
data = new int[10][];
data[0] = new int[5];
data[1] = new int[20];
System.out.println("data.length = " + data.length);
System.out.println("data[0].length = " + data[0].length);
System.out.println("data[1].length = " + data[1].length);
}
}
Array Copy Demo
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution 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.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
public class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { "d", "e", "c", "a", "f", "f", "e", "i", "n", "a",
"t", "e", "d" };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
Array Hunt game
/*
* 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.Random;
/**
* Array Hunt "game" (pathetic: computer plays itself).
*
* @author Ian Darwin
* @version $Id: ArrayHunt.java,v 1.3 2004/03/08 00:11:18 ian Exp $
*/
public class ArrayHunt {
/** the maximum (and actual) number of random ints to allocate */
protected final static int MAX = 4000;
/** the value to look for */
protected final static int NEEDLE = 1999;
int[] haystack;
Random r;
public static void main(String[] argv) {
ArrayHunt h = new ArrayHunt();
if (argv.length == 0)
h.play();
else {
int won = 0;
int games = Integer.parseInt(argv[0]);
for (int i = 0; i < games; i++)
if (h.play())
++won;
System.out
.println("Computer won " + won + " out of " + games + ".");
}
}
/** Construct the hunting ground */
public ArrayHunt() {
haystack = new int[MAX];
r = new Random();
}
/** Play one game. */
public boolean play() {
int i;
// Fill the array with random data (hay?)
for (i = 0; i < MAX; i++) {
haystack[i] = (int) (r.nextFloat() * MAX);
}
// Precondition for binary search is that data be sorted!
Arrays.sort(haystack);
// Look for needle in haystack
i = Arrays.binarySearch(haystack, NEEDLE);
if (i >= 0) { // Found it, we win.
System.out.println("Value " + NEEDLE + " occurs at haystack[" + i
+ "]");
return true;
} else { // Not found, we lose.
System.out.println("Value " + NEEDLE
+ " does not occur in haystack; nearest value is "
+ haystack[-(i + 2)] + " (found at " + -(i + 2) + ")");
return false;
}
}
}
Array initialization
// : c04:ArrayInit.java
// Array initialization.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class ArrayInit {
public static void main(String[] args) {
Integer[] a = { new Integer(1), new Integer(2), new Integer(3), };
Integer[] b = new Integer[] { new Integer(1), new Integer(2),
new Integer(3), };
}
} ///:~
Array Initializers
public class Main {
public static void main(String[] args) {
int[] odds = { 1, 3, 5, 7, 9 };
System.out.println("odds.length = " + odds.length);
for (int i = 0; i < odds.length; i++) {
System.out.println("odds[" + i + "] = " + odds[i]);
}
String[] daysOfWeek = { "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday" };
System.out.println("\ndaysOfWeek.length = " + daysOfWeek.length);
for (int i = 0; i < daysOfWeek.length; i++) {
System.out.println("daysOfWeek[" + i + "] = " + daysOfWeek[i]);
}
}
}
ArrayListDemo done over using an ArrayList
/*
* 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.ArrayList;
/**
* ArrayListDemo done over using an ArrayList
*/
public class ArrayListDemo {
public static void main(String[] argv) {
ArrayList al = new ArrayList();
// Create a source of Objects
StructureDemo source = new StructureDemo(15);
// Add lots of elements to the ArrayList...
al.add(source.getDate());
al.add(source.getDate());
al.add(source.getDate());
// First print them out using a for loop.
System.out.println("Retrieving by index:");
for (int i = 0; i < al.size(); i++) {
System.out.println("Element " + i + " = " + al.get(i));
}
}
}
Array Of Arrays Demo 2
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution 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.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
public class ArrayOfArraysDemo2 {
public static void main(String[] args) {
int[][] aMatrix = new int[4][];
//populate matrix
for (int i = 0; i < aMatrix.length; i++) {
aMatrix[i] = new int[5]; //create sub-array
for (int j = 0; j < aMatrix[i].length; j++) {
aMatrix[i][j] = i + j;
}
}
//print matrix
for (int i = 0; i < aMatrix.length; i++) {
for (int j = 0; j < aMatrix[i].length; j++) {
System.out.print(aMatrix[i][j] + " ");
}
System.out.println();
}
}
}
Arrays of primitives
// : c04:Arrays.java
// Arrays of primitives.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class Arrays {
public static void main(String[] args) {
int[] a1 = { 1, 2, 3, 4, 5 };
int[] a2;
a2 = a1;
for (int i = 0; i < a2.length; i++)
a2[i]++;
for (int i = 0; i < a1.length; i++)
System.out.println("a1[" + i + "] = " + a1[i]);
}
} ///:~
Can you change the .length of an array
/*
* 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.
*/
/**
* Can you change the .length of an array?
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: ChangeArrayLength.java,v 1.5 2004/02/09 03:33:53 ian Exp $
*/
public class ChangeArrayLength {
public static void main(String[] argv) {
//+
int[] a = new int[4];
System.out.println(a.length);
a.length = 5; // EXPECT COMPILE ERROR
//-
}
}
Clone Array
public class CloneArray {
public static void main(String args[]) {
int array1[] = { 1, 2, 3, 4, 5 };
int array2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.println("Original size: " + array1.length);
System.out.println("New size: " + cloneArray(array1).length);
System.out.println("Original size: " + array2.length);
System.out.println("New size: " + cloneArray(array2).length);
}
static int[] cloneArray(int original[]) {
return (int[]) original.clone();
}
}
Convert array of primitives into array of objects
import org.apache.rumons.lang.ArrayUtils;
public class Main {
public static void main(String[] args) {
int numbers[] = { 1, 2, 3, 4, 5 };
boolean bools[] = { true, false, false, true };
float decimals[] = { 10.1f, 3.14f, 2.17f };
Integer numbersObj[] = ArrayUtils.toObject(numbers);
Boolean boolsObj[] = ArrayUtils.toObject(bools);
Float decimalsObj[] = ArrayUtils.toObject(decimals);
}
}
Copy an array
public class Main {
public static void main(String[] args) {
int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int[] arrayCopy = new int[intArray.length];
System.arraycopy(intArray, 0, arrayCopy, 0, intArray.length);
for (int i = 0; i < arrayCopy.length; i++)
System.out.println(arrayCopy[i]);
}
}
/*
1
2
3
4
5
6
7
8
9
0
*/
Copying Elements from One Array to Another
public class Main {
public static void main(String[] argv) throws Exception {
int[] src = { 1, 2, 3 };
int[] dst = { 1, 1, 1 };
System.arraycopy(src, 0, dst, 0, Math.min(src.length, dst.length));
}
}
Create a repeated sequence of character
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
char c = "x";
int length = 10;
// creates char array with 10 elements
char[] chars = new char[length];
// fill each element of chars array with "x"
Arrays.fill(chars, c);
// print out the repeated "x"
System.out.println(String.valueOf(chars));
}
}
Create multidimension arrays
// : c04:MultiDimArray.java
// Creating multidimensional arrays.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.Random;
public class MultiDimArray {
static Random rand = new Random();
public static void main(String[] args) {
int[][] a1 = { { 1, 2, 3, }, { 4, 5, 6, }, };
for (int i = 0; i < a1.length; i++)
for (int j = 0; j < a1[i].length; j++)
System.out.println("a1[" + i + "][" + j + "] = " + a1[i][j]);
// 3-D array with fixed length:
int[][][] a2 = new int[2][2][4];
for (int i = 0; i < a2.length; i++)
for (int j = 0; j < a2[i].length; j++)
for (int k = 0; k < a2[i][j].length; k++)
System.out.println("a2[" + i + "][" + j + "][" + k + "] = "
+ a2[i][j][k]);
// 3-D array with varied-length vectors:
int[][][] a3 = new int[rand.nextInt(7)][][];
for (int i = 0; i < a3.length; i++) {
a3[i] = new int[rand.nextInt(5)][];
for (int j = 0; j < a3[i].length; j++)
a3[i][j] = new int[rand.nextInt(5)];
}
for (int i = 0; i < a3.length; i++)
for (int j = 0; j < a3[i].length; j++)
for (int k = 0; k < a3[i][j].length; k++)
System.out.println("a3[" + i + "][" + j + "][" + k + "] = "
+ a3[i][j][k]);
// Array of nonprimitive objects:
Integer[][] a4 = { { new Integer(1), new Integer(2) },
{ new Integer(3), new Integer(4) },
{ new Integer(5), new Integer(6) }, };
for (int i = 0; i < a4.length; i++)
for (int j = 0; j < a4[i].length; j++)
System.out.println("a4[" + i + "][" + j + "] = " + a4[i][j]);
Integer[][] a5;
a5 = new Integer[3][];
for (int i = 0; i < a5.length; i++) {
a5[i] = new Integer[3];
for (int j = 0; j < a5[i].length; j++)
a5[i][j] = new Integer(i * j);
}
for (int i = 0; i < a5.length; i++)
for (int j = 0; j < a5[i].length; j++)
System.out.println("a5[" + i + "][" + j + "] = " + a5[i][j]);
// Output test
int ln = 0;
for (int i = 0; i < a3.length; i++)
for (int j = 0; j < a3[i].length; j++)
for (int k = 0; k < a3[i][j].length; k++)
ln++;
}
} ///:~
Creating an array of nonprimitive objects
// : c04:ArrayClassObj.java
// Creating an array of nonprimitive objects.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.Random;
public class ArrayClassObj {
static Random rand = new Random();
public static void main(String[] args) {
Integer[] a = new Integer[rand.nextInt(20)];
System.out.println("length of a = " + a.length);
for (int i = 0; i < a.length; i++) {
a[i] = new Integer(rand.nextInt(500));
System.out.println("a[" + i + "] = " + a[i]);
}
}
} ///:~
Creating arrays with new
// : c04:ArrayNew.java
// Creating arrays with new.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.Random;
public class ArrayNew {
static Random rand = new Random();
public static void main(String[] args) {
int[] a;
a = new int[rand.nextInt(20)];
System.out.println("length of a = " + a.length);
for (int i = 0; i < a.length; i++)
System.out.println("a[" + i + "] = " + a[i]);
}
} ///:~
Creating a Two-Dimensional Array
/*This example creates a two-dimensional array with 9 rows and a variable number
of columns for each row. The first row is given 21 columns. The second row is
given 5000 columns.
*/
public class Test2Darray2 {
public static void main(String args[]) {
int[][] multD = new int[9][];
multD[0] = new int[21];
multD[1] = new int[5000];
}
}
Define array for class
public class EmployeeTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 3500);
staff[1] = new Employee("Carl Cracker", 7500);
staff[2] = new Employee("Tony Tester", 3800);
for (int i = 0; i < 3; i++)
staff[i].print();
}
}
class Employee {
private String name;
private double salary;
public Employee(String n, double s) {
name = n;
salary = s;
}
public void print() {
System.out.println(name + " " + salary);
}
}
Doubling the size of an array
public class DoubleArray {
public static void main(String args[]) {
int a1[] = { 1, 2, 3, 4, 5 };
int a2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.println("Original size: " + a1.length);
System.out.println("New size: " + doubleArray(a1).length);
System.out.println("Original size: " + a2.length);
System.out.println("New size: " + doubleArray(a2).length);
}
static int[] doubleArray(int original[]) {
int length = original.length;
int newArray[] = new int[length * 2];
System.arraycopy(original, 0, newArray, 0, length);
return newArray;
}
}
Dump array content: Convert the array to a List and then convert to String
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
String s[] = {"a", "b", "c", "d"};
System.out.println(Arrays.asList(s).toString());
}
}
Dump 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));
}
}
Extend the size of an array
public class Main {
public static void main(String[] args) {
String[] names = new String[] { "A", "B", "C" };
String[] extended = new String[5];
extended[3] = "D";
extended[4] = "F";
System.arraycopy(names, 0, extended, 0, names.length);
for (String str : extended)
System.out.println(str);
}
}
/*
A
B
C
D
F
*/
Get array upperbound
public class Main {
public static void main(String args[]) {
String[][] data = new String[3][4];
System.out.println("Dimension 1: " + data.length);
System.out.println("Dimension 2: " + data[0].length);
}
}
/*
Dimension 1: 3
Dimension 2: 4
*/
Grow array
import java.lang.reflect.Array;
public class ArrayGrowTest {
public static void main(String[] args) {
int[] a = { 1, 2, 3 };
a = (int[]) arrayGrow(a);
arrayPrint(a);
}
static Object arrayGrow(Object a) {
Class cl = a.getClass();
if (!cl.isArray())
return null;
Class componentType = a.getClass().getComponentType();
int length = Array.getLength(a);
int newLength = length + 10;
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, length);
return newArray;
}
static void arrayPrint(Object a) {
Class cl = a.getClass();
if (!cl.isArray())
return;
Class componentType = a.getClass().getComponentType();
int length = Array.getLength(a);
System.out.println(componentType.getName() + "[" + length + "]");
for (int i = 0; i < length; i++)
System.out.println(Array.get(a, i));
}
}
Initialization and re-assignment of arrays
// : c11:ArraySize.java
//Initialization & re-assignment of arrays.
//From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
//www.BruceEckel.ru. See copyright notice in CopyRight.txt.
class Weeble {
} // A small mythical creature
public class ArraySize {
public static void main(String[] args) {
// Arrays of objects:
Weeble[] a; // Local uninitialized variable
Weeble[] b = new Weeble[5]; // Null references
Weeble[] c = new Weeble[4];
for (int i = 0; i < c.length; i++)
if (c[i] == null) // Can test for null reference
c[i] = new Weeble();
// Aggregate initialization:
Weeble[] d = { new Weeble(), new Weeble(), new Weeble() };
// Dynamic aggregate initialization:
a = new Weeble[] { new Weeble(), new Weeble() };
System.out.println("a.length=" + a.length);
System.out.println("b.length = " + b.length);
// The references inside the array are
// automatically initialized to null:
for (int i = 0; i < b.length; i++)
System.out.println("b[" + i + "]=" + b[i]);
System.out.println("c.length = " + c.length);
System.out.println("d.length = " + d.length);
a = d;
System.out.println("a.length = " + a.length);
// Arrays of primitives:
int[] e; // Null reference
int[] f = new int[5];
int[] g = new int[4];
for (int i = 0; i < g.length; i++)
g[i] = i * i;
int[] h = { 11, 47, 93 };
// Compile error: variable e not initialized:
//!System.out.println("e.length=" + e.length);
System.out.println("f.length = " + f.length);
// The primitives inside the array are
// automatically initialized to zero:
for (int i = 0; i < f.length; i++)
System.out.println("f[" + i + "]=" + f[i]);
System.out.println("g.length = " + g.length);
System.out.println("h.length = " + h.length);
e = h;
System.out.println("e.length = " + e.length);
e = new int[] { 1, 2 };
System.out.println("e.length = " + e.length);
}
} ///:~
Initialize a static array
public class Main {
static Integer[] integerArray;
static {
integerArray = new Integer[] { new Integer(1), new Integer(2) };
}
public static void main(String args[]) {
for (int i = 0; i < integerArray.length; i++) {
System.out.println(integerArray[i]);
}
}
}
Initialize multidimensional array
public class Main {
static double[][] d = { { 4.6, 8.5, 3.2, 5.1 }, { 6.4, 11.1, 4.1, 6.2 } };
public static void main(String args[]) {
}
}
Initializing Array Values
/*
This example creates a four element array with 1, 2, 3, 4 as the values.
The length of the array, and the element at index 2, are printed out.
*/
public class TestArray {
public static void main(String args[]) {
int[] data = {
1, 2, 3, 4
};
System.out.println("The length of the array is " + data.length);
System.out.println("The element at index 2 is " + data[2]);
}
}
Initializing a Two Dimensional Array
//A two dimensional array of int values is initialized, and the element
//at [0][2] is displayed.
public class Test2Darray {
public static void main(String args[]) {
int[][] multiD = {
{ 1, 2, 3, 4 },
{ 5, 6, 7 }
};
System.out.println("The element at [0][2] is " + multiD[0][2]);
}
}
Java program to demonstrate multidimensional arrays
/*
Java Programming for Engineers
Julio Sanchez
Maria P. Canton
ISBN: 0849308100
Publisher: CRC Press
*/
// File name: MultiArray.java
//Reference: Chapter 6
//
//Java program to demonstrate multidimensional arrays
//Topics:
// 1. Simultaneous declaration and initialization
// 2. Use of the length operator to obtain the size
// of multidimensional arrays
public class MultiArray {
// Declare constants
final static int ROWS = 10;
final static int COLS = 5;
public static void main(String[] args) {
// Local varaibles
int rowCount;
int colCount;
int totalSize;
// Declare and allocate an array of bytes
byte[][] screenPix = new byte[ROWS][COLS];
// Obtain and store array dimensions
rowCount = screenPix.length;
colCount = screenPix[COLS].length;
totalSize = rowCount * colCount;
// To obtain the total number of elements of a
// two-dimensional ragged array you need to get the size of
// each array dimension separately
// Display array dimensions
System.out.println("Array row size: " + rowCount);
System.out.println("Array column size: " + colCount);
System.out.println("Total size: " + totalSize);
//*************************
// ragged arrays
//*************************
// First allocate the rows of an array
byte[][] raggedArray = new byte[5][];
// Now allocate the columns
raggedArray[0] = new byte[2];
raggedArray[1] = new byte[2];
raggedArray[2] = new byte[4];
raggedArray[3] = new byte[8];
raggedArray[4] = new byte[3];
// The resulting ragged array is as follows:
// x x
// x x
// x x x x
// x x x x x x x x
// x x x
//************************************
// static array initialization
//************************************
byte[][] smallArray = { { 10, 11, 12, 13 }, { 20, 21, 22, 23 },
{ 30, 31, 32, 33 }, { 40, 41, 42, 43 }, };
// Display the array element at row 2, column 3
System.out.println(smallArray[1][2]); // Value is 21
}
}
java.utils.Arrays provides ways to dump the content of an array.
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));
}
}
Multi Dimension Array
public class MultiArray1 {
public static void main(String args[]) {
// int array[][] = {{1,2,3}, {4,5,6}, {7,8,9}};
// int []array[] = {{1,2,3}, {4,5,6}, {7,8,9}};
// System.out.println(array[0][0]);
// System.out.println(array[1][0]);
// System.out.println(array[2][0]);
// System.out.println([0][0]array);
// System.out.println([1][0]array);
// System.out.println([2][0]array);
Object events[][] = { { new Integer(1452), new String("Italy") },
{ new Integer(1472), new String("b.jpg") },
{ new Integer(1483), new String("Hr") },
{ new Integer(1495), new String("Pte") },
{ new Integer(1503), new String("m.jpg") },
{ new Integer(1519), new String("F") } };
}
}
Multiply two matrices
/**
* Multiply two matrices.
* Only defined for int: TODO: rewrite using 1.5 Generics to add
* support for long, float, and double.
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: Matrix.java,v 1.4 2004/03/07 02:53:53 ian Exp $
*/
public class Matrix {
/* Matrix-multiply two arrays together.
* The arrays MUST be rectangular.
* @author Tom Christiansen & Nathan Torkington, Perl Cookbook version.
*/
public static int[][] multiply(int[][] m1, int[][] m2) {
int m1rows = m1.length;
int m1cols = m1[0].length;
int m2rows = m2.length;
int m2cols = m2[0].length;
if (m1cols != m2rows)
throw new IllegalArgumentException("matrices don"t match: " + m1cols + " != " + m2rows);
int[][] result = new int[m1rows][m2cols];
// multiply
for (int i=0; i<m1rows; i++)
for (int j=0; j<m2cols; j++)
for (int k=0; k<m1cols; k++)
result[i][j] += m1[i][k] * m2[k][j];
return result;
}
/** Matrix print.
*/
public static void mprint(int[][] a) {
int rows = a.length;
int cols = a[0].length;
System.out.println("array["+rows+"]["+cols+"] = {");
for (int i=0; i<rows; i++) {
System.out.print("{");
for (int j=0; j<cols; j++)
System.out.print(" " + a[i][j] + ",");
System.out.println("},");
}
System.out.println(":;");
}
public static void main(String[] argv) {
//+
int x[][] = {
{ 3, 2, 3 },
{ 5, 9, 8 },
};
int y[][] = {
{ 4, 7 },
{ 9, 3 },
{ 8, 1 },
};
int z[][] = Matrix.multiply(x, y);
Matrix.mprint(x);
Matrix.mprint(y);
Matrix.mprint(z);
//-
}
}
Reinitializes a byte array
/*
* $RCSfile: ArrayUtil.java,v $
* $Revision: 1.1 $
* $Date: 2005/02/11 05:02:24 $
* $State: Exp $
*
* Class: ArrayUtil
*
* Description: Utillities for arrays.
*
*
*
* COPYRIGHT:
*
* This software module was originally developed by Raphaël Grosbois and
* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
* Centre France S.A) in the course of development of the JPEG2000
* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
* software module is an implementation of a part of the JPEG 2000
* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
* Systems AB and Canon Research Centre France S.A (collectively JJ2000
* Partners) agree not to assert against ISO/IEC and users of the JPEG
* 2000 Standard (Users) any of their rights under the copyright, not
* including other intellectual property rights, for this software module
* with respect to the usage by ISO/IEC and Users of this software module
* or modifications thereof for use in hardware or software products
* claiming conformance to the JPEG 2000 Standard. Those intending to use
* this software module in hardware or software products are advised that
* their use may infringe existing patents. The original developers of
* this software module, JJ2000 Partners and ISO/IEC assume no liability
* for use of this software module or modifications thereof. No license
* or right to this software module is granted for non JPEG 2000 Standard
* conforming products. JJ2000 Partners have full right to use this
* software module for his/her own purpose, assign or donate this
* software module to any third party and to inhibit third parties from
* using this software module for non JPEG 2000 Standard conforming
* products. This copyright notice must be included in all copies or
* derivative works of this software module.
*
* Copyright (c) 1999/2000 JJ2000 Partners.
*
*
*
*/
/**
* This class contains a colleaction of utility static methods for arrays.
* */
public class ArrayUtil {
/** The maximum array size to do element by element copying, larger
* arrays are copyied in a n optimized way. */
public static final int MAX_EL_COPYING = 8;
/** The number of elements to copy initially in an optimized array copy */
public static final int INIT_EL_COPYING = 4;
/**
* Reinitializes an int array to the given value in an optimized way. If
* the length of the array is less than MAX_EL_COPYING, then the array
* is set element by element in the normal way, otherwise the first
* INIT_EL_COPYING elements are set element by element and then
* System.arraycopy is used to set the other parts of the array.
*
* @param arr The array to set.
*
* @param val The value to set the array to.
*
*
* */
public static void intArraySet(int arr[], int val) {
int i,len,len2;
len = arr.length;
// Set array to "val" in an optimized way
if (len < MAX_EL_COPYING) {
// Not worth doing optimized way
for (i=len-1; i>=0; i--) { // Set elements
arr[i] = val;
}
}
else { // Do in optimized way
len2 = len>>1;
for (i=0; i<INIT_EL_COPYING; i++) { // Set first elements
arr[i] = val;
}
for (; i <= len2 ; i<<=1) {
// Copy values doubling size each time
System.arraycopy(arr,0,arr,i,i);
}
if (i < len) { // Copy values to end
System.arraycopy(arr,0,arr,i,len-i);
}
}
}
/**
* Reinitializes a byte array to the given value in an optimized way. If
* the length of the array is less than MAX_EL_COPYING, then the array
* is set element by element in the normal way, otherwise the first
* INIT_EL_COPYING elements are set element by element and then
* System.arraycopy is used to set the other parts of the array.
*
* @param arr The array to set.
*
* @param val The value to set the array to.
*
*
* */
public static void byteArraySet(byte arr[], byte val) {
int i,len,len2;
len = arr.length;
// Set array to "val" in an optimized way
if (len < MAX_EL_COPYING) {
// Not worth doing optimized way
for (i=len-1; i>=0; i--) { // Set elements
arr[i] = val;
}
}
else { // Do in optimized way
len2 = len>>1;
for (i=0; i<INIT_EL_COPYING; i++) { // Set first elements
arr[i] = val;
}
for (; i <= len2 ; i<<=1) {
// Copy values doubling size each time
System.arraycopy(arr,0,arr,i,i);
}
if (i < len) { // Copy values to end
System.arraycopy(arr,0,arr,i,len-i);
}
}
}
}
Reinitializes an int array
/*
* $RCSfile: ArrayUtil.java,v $
* $Revision: 1.1 $
* $Date: 2005/02/11 05:02:24 $
* $State: Exp $
*
* Class: ArrayUtil
*
* Description: Utillities for arrays.
*
*
*
* COPYRIGHT:
*
* This software module was originally developed by Raphaël Grosbois and
* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
* Centre France S.A) in the course of development of the JPEG2000
* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
* software module is an implementation of a part of the JPEG 2000
* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
* Systems AB and Canon Research Centre France S.A (collectively JJ2000
* Partners) agree not to assert against ISO/IEC and users of the JPEG
* 2000 Standard (Users) any of their rights under the copyright, not
* including other intellectual property rights, for this software module
* with respect to the usage by ISO/IEC and Users of this software module
* or modifications thereof for use in hardware or software products
* claiming conformance to the JPEG 2000 Standard. Those intending to use
* this software module in hardware or software products are advised that
* their use may infringe existing patents. The original developers of
* this software module, JJ2000 Partners and ISO/IEC assume no liability
* for use of this software module or modifications thereof. No license
* or right to this software module is granted for non JPEG 2000 Standard
* conforming products. JJ2000 Partners have full right to use this
* software module for his/her own purpose, assign or donate this
* software module to any third party and to inhibit third parties from
* using this software module for non JPEG 2000 Standard conforming
* products. This copyright notice must be included in all copies or
* derivative works of this software module.
*
* Copyright (c) 1999/2000 JJ2000 Partners.
*
*
*
*/
/**
* This class contains a colleaction of utility static methods for arrays.
* */
public class ArrayUtil {
/** The maximum array size to do element by element copying, larger
* arrays are copyied in a n optimized way. */
public static final int MAX_EL_COPYING = 8;
/** The number of elements to copy initially in an optimized array copy */
public static final int INIT_EL_COPYING = 4;
/**
* Reinitializes an int array to the given value in an optimized way. If
* the length of the array is less than MAX_EL_COPYING, then the array
* is set element by element in the normal way, otherwise the first
* INIT_EL_COPYING elements are set element by element and then
* System.arraycopy is used to set the other parts of the array.
*
* @param arr The array to set.
*
* @param val The value to set the array to.
*
*
* */
public static void intArraySet(int arr[], int val) {
int i,len,len2;
len = arr.length;
// Set array to "val" in an optimized way
if (len < MAX_EL_COPYING) {
// Not worth doing optimized way
for (i=len-1; i>=0; i--) { // Set elements
arr[i] = val;
}
}
else { // Do in optimized way
len2 = len>>1;
for (i=0; i<INIT_EL_COPYING; i++) { // Set first elements
arr[i] = val;
}
for (; i <= len2 ; i<<=1) {
// Copy values doubling size each time
System.arraycopy(arr,0,arr,i,i);
}
if (i < len) { // Copy values to end
System.arraycopy(arr,0,arr,i,len-i);
}
}
}
/**
* Reinitializes a byte array to the given value in an optimized way. If
* the length of the array is less than MAX_EL_COPYING, then the array
* is set element by element in the normal way, otherwise the first
* INIT_EL_COPYING elements are set element by element and then
* System.arraycopy is used to set the other parts of the array.
*
* @param arr The array to set.
*
* @param val The value to set the array to.
*
*
* */
public static void byteArraySet(byte arr[], byte val) {
int i,len,len2;
len = arr.length;
// Set array to "val" in an optimized way
if (len < MAX_EL_COPYING) {
// Not worth doing optimized way
for (i=len-1; i>=0; i--) { // Set elements
arr[i] = val;
}
}
else { // Do in optimized way
len2 = len>>1;
for (i=0; i<INIT_EL_COPYING; i++) { // Set first elements
arr[i] = val;
}
for (; i <= len2 ; i<<=1) {
// Copy values doubling size each time
System.arraycopy(arr,0,arr,i,i);
}
if (i < len) { // Copy values to end
System.arraycopy(arr,0,arr,i,len-i);
}
}
}
}
Resize an array, System.arraycopy()
import java.lang.reflect.Array;
public class Main {
public static void main(String arg[]) {
String[] s = (String[]) expand(new String[20]);
System.out.println(s.length);
}
public static Object expand(Object a) {
Class cl = a.getClass();
if (!cl.isArray())
return a;
int length = Array.getLength(a);
int newLength = 1000;
Class componentType = a.getClass().getComponentType();
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, length);
return newArray;
}
}
Reverse array elements order
import org.apache.rumons.lang.ArrayUtils;
public class Main {
public static void main(String[] args) {
String[] colors = { "Red", "Green", "Blue", "Cyan", "Yellow", "Magenta" };
System.out.println(ArrayUtils.toString(colors));
ArrayUtils.reverse(colors);
System.out.println(ArrayUtils.toString(colors));
}
}
Show Two-Dimensional Array of Objects
/*
* 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.
*/
/** Show Two-Dimensional Array of Objects */
public class ArrayTwoDObjects {
/** Return list of subscript names (unrealistic; just for demo). */
public static String[][] getArrayInfo() {
String info[][];
info = new String[10][10];
for (int i=0; i < info.length; i++) {
for (int j = 0; j < info[i].length; j++) {
info[i][j] = "String[" + i + "," + j + "]";
}
}
return info;
}
/** Return list of allowable parameters (Applet method). */
public static String[][] getParameterInfo() {
String param_info[][] = {
{"fontsize", "9-18", "Size of font"},
{"URL", "-", "Where to download"},
};
return param_info;
}
/** Run both initialization methods and print part of the results */
public static void main(String[] args) {
print("from getArrayInfo", getArrayInfo());
print("from getParameterInfo", getParameterInfo());
}
/** Print selected elements from the 2D array */
public static void print(String tag, String[][] array) {
System.out.println("Array " + tag + " is " + array.length + " x " +
array[0].length);
System.out.println("Array[0][0] = " + array[0][0]);
System.out.println("Array[0][1] = " + array[0][1]);
System.out.println("Array[1][0] = " + array[1][0]);
System.out.println("Array[0][0] = " + array[0][0]);
System.out.println("Array[1][1] = " + array[1][1]);
}
}
String array and output to console
public class Welcome {
public static void main(String[] args) {
String[] greeting = new String[3];
greeting[0] = "This is the greeting";
greeting[1] = "from";
greeting[2] = "Java Source and Support.";
for (int i = 0; i < greeting.length; i++)
System.out.println(greeting[i]);
}
}
Sum all elements in the array
/*
* Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
*
* Project: OpenSubsystems
*
* $Id: ArrayUtils.java,v 1.9 2007/01/23 06:00:30 bastafidli Exp $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* Collection of useful utilities to work with arrays.
*
* @version $Id: ArrayUtils.java,v 1.9 2007/01/23 06:00:30 bastafidli Exp $
* @author Peter Satury
* @code.reviewer Miro Halas
* @code.reviewed 1.5 2005/07/29 07:36:24 bastafidli
*/
public final class ArrayUtils
{
/**
* Private constructor since this class cannot be instantiated
*/
private ArrayUtils(
)
{
// Do nothing
}
// Public methods ///////////////////////////////////////////////////////////
/**
* Method to exclude 2 arrays of ints so that the result contains all elements
* from the first array, which are not in the second array.
*
* @param arrBase - base array to exclude from
* @param arrExclude - array to exclude from the first one
* @return int[] - array which contains all elements from the first array
* which are not in the second array or null
*/
public static int[] exclude(
int[] arrBase,
int[] arrExclude
)
{
int[] arrReturn = null;
if ((arrBase != null) && (arrBase.length > 0) && (arrExclude != null)
&& (arrExclude.length > 0))
{
int[] arrHelp;
int iCount1;
int iHelp;
int iLength = 0;
arrHelp = new int[arrBase.length];
for (iCount1 = 0; iCount1 < arrBase.length; iCount1++)
{
iHelp = arrBase[iCount1];
if (ArrayUtils.contains(arrExclude, iHelp) == -1)
{
// If the element is not part of the second array then it should
// be included in the result
arrHelp[iLength++] = iHelp;
}
}
// Shrink the array
// TODO: Performance: Replace this with System.arraycopy
arrReturn = new int[iLength];
for (int iCount = 0; iCount < iLength; iCount++)
{
arrReturn[iCount] = arrHelp[iCount];
}
}
else
{
arrReturn = arrBase;
}
return arrReturn;
}
/**
* Test if specified array contains given element and if it does, find
* its position.
*
* @param source - array to search, can be null
* @param iTarget - element to find
* @return int - -1 if it doesn"t exist there otherwise its position
*/
public static int contains(
int[] source,
int iTarget
)
{
int iReturn = -1;
if ((source != null) && (source.length > 0))
{
int iIndex;
for (iIndex = 0; iIndex < source.length; iIndex++)
{
if (source[iIndex] == iTarget)
{
iReturn = iIndex;
break;
}
}
}
return iReturn;
}
/**
* Sum all elements in the array.
*
* @param source - array to sum elements of
* @return long - sum of the elements in the array
*/
public static long sum(
int[] source
)
{
int iReturn = 0;
if ((source != null) && (source.length > 0))
{
int iIndex;
for (iIndex = 0; iIndex < source.length; iIndex++)
{
iReturn += source[iIndex];
}
}
return iReturn;
}
}
Timing array loop performance
public class TimeArray {
public static void main(String args[]) {
long startTime = System.currentTimeMillis();
for (int i = 0, n = Integer.MAX_VALUE; i < n; i++) {
;
}
long midTime = System.currentTimeMillis();
for (int i = Integer.MAX_VALUE - 1; i >= 0;) {
;
}
long endTime = System.currentTimeMillis();
System.out.println("Increasing: " + (midTime - startTime));
System.out.println("Decreasing: " + (endTime - midTime));
}
}
To get the number of dimensions
public class Main {
public static void main(String args[]) {
String[][] data = new String[3][4];
System.out.println(getDimension(data));
}
public static int getDimension(Object array) {
int dim = 0;
Class c = array.getClass();
while (c.isArray()) {
c = c.getComponentType();
dim++;
}
return (dim);
}
}
//2
Triangular array
import java.text.Format;
public class TriangularArray {
public static void main(String[] args) {
final int MAX_HIGH = 10;
// allocate triangular array
int[][] odds = new int[MAX_HIGH + 1][];
for (int i = 0; i <= MAX_HIGH; i++)
odds[i] = new int[i + 1];
// fill triangular array
for (int i = 0; i < odds.length; i++)
for (int j = 0; j < odds[i].length; j++)
odds[i][j] = i+j;
// print triangular array
for (int i = 0; i < odds.length; i++) {
for (int j = 0; j < odds[i].length; j++){
System.out.print(odds[i][j] + " ");
}
System.out.println();
}
}
}
Use the new shorthand notation to iterate through an array
public class Main {
public static void main(String args[]) {
String s[] = { "a", "b", "c", "d" };
for (String element : s)
System.out.println(element);
}
}
Using the length Variable
//The length variable is used to access the length of the firstrowof a
//two dimensional array.
public class TestLength {
public static void main(String args[]) {
int[][] multiD = {
{ 1, 2, 3, 4 },
{ 5, 6, 7 }
};
System.out.println("The length of the first row is "+multiD[0].length);
}
}