There are three main differences between JAVA arrays and container classes: efficiency, type, and the ability to save basic types . In JAVA, arrays are the most efficient way to store and randomly access a sequence of object references. An array is a simple linear sequence, which makes element access very fast. But the price paid for this is that the size of the array is fixed and cannot be changed during its lifetime.
Thanks to generics and automatic packaging mechanisms, containers can now be used with primitive types almost as easily as arrays. Both arrays and containers can prevent you from abusing them to a certain extent. If they go out of bounds, you will get a RuntimeException. The only remaining advantage of arrays is efficiency. However, if you want to solve more general problems, arrays may be too restrictive, so in this case most people will still choose containers.
Therefore, if you are using recent JAVA versions, you should prefer containers over arrays. Programs should only be refactored to arrays if performance has proven to be an issue and switching to arrays improves performance.
【initialization】
JAVA has very strict regulations on array initialization, which can effectively prevent the abuse of arrays. If there is an initialization error, you will get CompileException instead of RuntimeException directly. Nothing can be done with this array reference until the array is properly initialized.
Array definitions include int[] array and int array[]. Generally, the first style is used to separate the type from the variable name.
There are two ways to initialize an array, static initialization and dynamic initialization. The length must be specified during initialization. The length of the first dimension of the multidimensional array must be pointed out, and it must be defined from high to low dimensions. The initialization action can be anywhere in the code, but the {} method can only appear where the array is created. See the program for specific initialization methods:
arrayA = new int[10]; //Dynamic initialization
System.out.println("arrayA length: " + arrayA.length);
int[] arrayC = new int[]{1,2,3,4};
System.out.println("arrayC length: " + arrayC.length);
//int[] arrayD = new int[1]{1}; //Wrong initialization, dimensions and initialization values cannot be defined at the same time
int[][] arrayE = new int[1][];
System.out.println("arrayE length: " + arrayE.length);
//int[][] arrayF = new int[][2]; //The length of the high dimension should be specified first
int[][] arrayG = new int[][]{{1,2,3,4},{5,6,7},{7,24,23,24}};
System.out.println("arrayG length: " + arrayG.length);
int[][][] arrayH = new int[][][]{{{1,2,3},{4,5,6},{7,8,9},{10,11,12} }};
System.out.println("arrayH length: " + arrayH.length);
dummyArray[] arrayI = {new dummyArray(),new dummyArray()}; //Custom array type
System.out.println("arrayI length: " + arrayI.length);
System.out.println("arrayI[1]: " + arrayI[1].getValue());
dummyArray[] arrayK = new dummyArray[5];
System.out.println("arrayK[0]: " + arrayK[0]); //null
for(int i = 0; i < arrayK.length; i++){
arrayK[i] = new dummyArray();
}
System.out.println("arrayK[0]: " + arrayK[0].getValue()); //2
}
}
class dummyArray{
private static int temp;
private final int arrayValue = temp++;
public int getValue(){
return arrayValue;
}
}
Output:
arrayB length: 5
arrayA length: 10
arrayC length: 4
arrayE length: 1
arrayG length: 3
arrayH length: 1
arrayI length: 2
arrayI[1]: 1
arrayK[0]: null
arrayK[0]: 2
int[][] arrayB = new int[10][];
System.out.println("arrayB length: " + arrayB.length);
int[][] arrayC = new int[][]{{1,1,1,2,},{1,1,2,3,4,5},{4,5,6,7,7} ,};//Pay attention to the comma after
System.out.println("arrayC length: " + arrayC.length);
int[][] arrayD = new int[][]{{1,1,1,2,},{1,1,2,3,4,5},{4,5,6,7,7} ,{}};
System.out.println("arrayD length: " + arrayD.length);
}
}
Output:
arrayA length: 15
arrayB length: 10
arrayC length: 3
arrayD length: 4
[Assignment and Reference]
When a JAVA array is initialized, it only has a reference to the array, and no storage space is allocated to the array. Therefore, copying between arrays cannot simply use "=" assignment, because the same object is operated. The following procedure:
}
}
Output:
I'm testA,I have no changed:testA
I'm arrayA, I have no changed:arrayB have changed
[Array copy]
How to copy an array in JAVA:
1. Use FOR loop to copy all or specified elements, which is less efficient.
2. Use the clone method to get the value of the array instead of a reference. However, clone cannot copy specified elements and has low flexibility.
3. Use the System.arraycopy(src, srcPos, dest, destPos, length) method. The Java standard class library provides the static method System.arraycopy(). Using it to copy an array is much faster than a for loop. System.arraycopy() is for All types are overloaded. Both basic type arrays and object arrays can be copied using System.arraycopy(), but object arrays only copy references, and there will be no two copies of objects. This is called shallow copy.
src: source array;
srcPos: the starting position of the source array to be copied;
dest: destination array;
destPos: the starting position where the destination array is placed;
length: The length of the copy.
Note: System.arraycopy() does not perform automatic packaging and automatic unpacking, so the two arrays must be of the same type or can be converted to arrays of the same type. At the same time, this method can also be used to copy the array itself.
int[] test ={0,1,2,3,4,5,6};
System.arraycopy(test,0,test,3,3);
The result is: {0,1,2,0,1,2,6};
The test procedure is as follows:
//clone method
int[] arrayB = new int[9];
arrayB = array.clone();
//test
arrayB[1] = 19;
for(int i = 0; i < arrayB.length; i++){
System.out.print(arrayB[i] + ",");
}
System.out.println("");
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + ",");
}
System.out.println("");
//System.arrayCopy method
int[] arrayC = new int[9];
System.arraycopy(array, 0, arrayC, 0, arrayC.length);
//test
arrayC[1] = 19;
for(int i = 0; i < arrayC.length; i++){
System.out.print(arrayC[i] + ",");
}
System.out.println("");
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + ",");
}
}
}
String[][] arrayD = {{"a","b"},{"c","d"}};
String[][] arrayE = {{"a","b"},{"c","d"}};
System.out.println(Arrays.deepEquals(arrayD, arrayE));
}
}
[return array]
C and C++ cannot return an array, only a pointer to the array, because returning an array makes it difficult to control the life cycle of the array and can easily cause memory leaks. Java allows returning an array directly, and it can be recycled by the garbage collection mechanism.
[Array and Container Conversion] [Unable to convert basic type array]
Convert array to List:
int[] arrayB = {1,2,3};
List listB = java.util.Arrays.asList(arrayB);
System.out.println("listB: " + listB);
Integer[] arrayC = {1,2,3};
List listC = java.util.Arrays.asList(arrayC);
System.out.println("listC: " + listC);
}
}
Output:
listA: [a, b, c]
listB: [[I@de6ced]
listC: [1, 2, 3]
Convert List to Array
String[] strings = new String[list.size()];
array = list.toArray(strings);
for(int i = 0, j = array.length; i < j; i++){
System.out.print(array[i] + ",");
}
}
}
The output is:
list: [testA, testB, testC]
testA,testB,testC
public static String[] arrayUnique(String[] array){
List<String> list = new ArrayList<String>();
for(int i = 0, j = array.length; i < j; i++){
if(!list.contains(array[i])){
list.add(array[i]);
}
}
String[] strings = new String[list.size()];
String[] arrayUnique = list.toArray(strings);
return arrayUnique;
}
}
Double[] arrayB = new Double[1000000];
for(int i = 0, j = arrayB.length; i < j; i++){
arrayB[i] = Math.ceil(Math.random()*1000);
}
System.out.println("start");
long startTime = System.currentTimeMillis();
arrayUnique(array);
long endTime = System.currentTimeMillis();
System.out.println("array unique run time: " +(endTime - startTime) +"ms");
long startTimeB = System.currentTimeMillis();
arrayUnique(arrayB);
long endTimeB = System.currentTimeMillis();
System.out.println("arrayB unique run time: " +(endTimeB - startTimeB) +"ms");
}
public static Double[] arrayUnique(Double[] array){
List<Double> list = new ArrayList<Double>();
for(int i = 0, j = array.length; i < j; i++){
if(!list.contains(array[i])){
list.add(array[i]);
}
}
Double[] doubles = new Double[list.size()];
Double[] arrayUnique = list.toArray(doubles);
return arrayUnique;
}
}
Output:
start
array unique run time: 577ms
arrayB unique run time: 5663ms