Java Tutorial/Collections/Array Basics
Содержание
- 1 Alternative Array Declaration Syntax
- 2 An array is a Java object
- 3 Anonymous arrays are declared similarly to regular arrays
- 4 Array Reallocation
- 5 Arrays of Characters
- 6 Changing Array Size
- 7 Circular Buffer
- 8 How to define an Array
- 9 Initializing array elements by index
- 10 Initializing Arrays
- 11 Merge (or add) two arrays into one
- 12 The Length of an Array
- 13 To reference the components of an array
- 14 Use System.arraycopy to duplicate array
- 15 Using a for loop to iterate over all the elements and set the values
- 16 Using the Collection-Based for Loop with an Array
Alternative Array Declaration Syntax
For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
An array is a Java object
public class MainClass {
static String[] names;
public static void main(String[] a) {
if (names == null) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
true
Anonymous arrays are declared similarly to regular arrays
new type[] {comma-delimited-list}
1 2 3 4 5
Array Reallocation
You can make a clone of an array and make the new array have a different size.
public static boolean[] copyOf (boolean[] original, int newLength)
public static byte[] copyOf (byte[] original, int newLength)
public static char[] copyOf (char[] original, int newLength)
public static double[] copyOf (double[] original, int newLength)
public static float [] copyOf (float[] original, int newLength)
public static int[] copyOf (int[] original, int newLength)
public static long[] copyOf (long[] original, int newLength)
public static short[] copyOf (short[] original, int newLength)
public static <T> T[] copyOf (T[] original, int newLength)
public static <T,U> T[] copyOf (U[] original, int newLength,java.lang.Class<? extends T[]> newType)
[1, 3, 5, 7, 9] [1, 3, 5, 7, 9, 11] [5, 7, 9, 0, 0, 0, 0, 0]
Arrays of Characters
public class MainClass{
public static void main(String[] arg){
char[] message = new char[50];
java.util.Arrays.fill(message, "A");
for(char ch: message){
System.out.println(ch);
}
}
}
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
Changing Array Size
Once an array is created, its size cannot be changed. If you want to change the size, you must create a new array and populates it using the values of the old array.
public class MainClass {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3 };
int[] temp = new int[4];
int length = numbers.length;
for (int j = 0; j < length; j++) {
temp[j] = numbers[j];
}
numbers = temp;
}
}
Circular Buffer
public class TestCircularBuffer {
public static void main(String args[]) {
TestCircularBuffer t = new TestCircularBuffer();
}
public TestCircularBuffer() {
CircularBuffer c = new CircularBuffer(8);
System.out.println("Storing: 1");
c.store(1);
System.out.println("Reading: " + c.read());
System.out.println("Storing: 2");
c.store(2);
System.out.println("Storing: 3");
c.store(3);
System.out.println("Storing: 4");
c.store(4);
System.out.println("Reading: " + c.read());
System.out.println("Reading: " + c.read());
System.out.println("Storing: 8");
c.store(8);
System.out.println("Storing: 9");
c.store(9);
System.out.println("Storing: 10");
c.store(10);
System.out.println("Storing: 11");
c.store(11);
System.out.println("Storing: 12");
c.store(12);
System.out.println("Reading: " + c.read());
System.out.println("Reading: " + c.read());
System.out.println("Reading: " + c.read());
System.out.println("Reading: " + c.read());
System.out.println("Reading: " + c.read());
System.out.println("Reading: " + c.read());
System.out.println("Reading: " + c.read());
System.out.println("Reading: " + c.read());
}
}
class CircularBuffer {
private Integer data[];
private int head;
private int tail;
public CircularBuffer(Integer number) {
data = new Integer[number];
head = 0;
tail = 0;
}
public boolean store(Integer value) {
if (!bufferFull()) {
data[tail++] = value;
if (tail == data.length) {
tail = 0;
}
return true;
} else {
return false;
}
}
public Integer read() {
if (head != tail) {
int value = data[head++];
if (head == data.length) {
head = 0;
}
return value;
} else {
return null;
}
}
private boolean bufferFull() {
if (tail + 1 == head) {
return true;
}
if (tail == (data.length - 1) && head == 0) {
return true;
}
return false;
}
}
How to define an Array
- An array is a named set of same-type variables.
- Each variable in the array is called an array element.
- The first element will have an index of 0.
public class MainClass {
public static void main(String[] arg) {
int[] intArray = new int[10];
for (int i = 0; i < 10; i++) {
intArray[i] = 100;
}
for (int i = 0; i < 10; i++) {
System.out.println(intArray[i]);
}
}
}
100 100 100 100 100 100 100 100 100 100
Initializing array elements by index
public class MainClass {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
April has 30 days.
Initializing Arrays
public class MainClass{
public static void main(String[] arg){
int[] primes = {2, 3, 5, 7, 11, 13, 17}; // An array of 7 elements
for (int i = 0; i < primes.length; i++) {
System.out.println(primes[i]);
}
}
}
2 3 5 7 11 13 17
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));
}
}
The Length of an Array
public class MainClass {
public static void main(String[] arg) {
int[] intArray = new int[10];
for (int i = 0; i < intArray.length; i++) {
intArray[i] = 100;
}
for (int i = 0; i < intArray.length; i++) {
System.out.println(intArray[i]);
}
}
}
100 100 100 100 100 100 100 100 100 100
To reference the components of an array
To reference the components of an array, use an index after the variable name. For example, the following snippet creates an array of four String objects and initializes its first member.
public class MainClass {
public static void main(String[] args) {
String[] names = new String[4];
names[0] = "Hello World";
}
}
Use System.arraycopy to duplicate array
/*
* Copyright (c) 1995 - 2008 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:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - 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.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*/
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));
}
}
Using a for loop to iterate over all the elements and set the values
public class MainClass {
public static void main(String[] arg) {
double[] data = new double[50]; // An array of 50 values of type double
for (int i = 0; i < data.length; i++) { // i from 0 to data.length-1
data[i] = 1.0;
}
for (int i = 0; i < data.length; i++) { // i from 0 to data.length-1
System.out.println(data[i]);
}
}
}
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
Using the Collection-Based for Loop with an Array
You can now use it to iterate over an array or a collection without the index. Use this syntax to iterate over an array:
for (componentType variable: arrayName)
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0