Home >Java >javaTutorial >Summary of Java Array Code Examples
This article mainly explains the knowledge about arrays in Java, mainly Arrays will be discussed in detail from five aspects: arrays and containers, array creation and initialization, arrays and generics, arrays and variable parameterlists, and the practical functions of Arrays tool classes. Description and summary.
Arrays and containers
Creation and creation of arrays Initialization
Arrays and generics
Arrays and variable parameter lists
Arrays tool class Practical functions
Summary
In Java, both arrays and containers You can hold objects, so what is the difference between arrays and containers? When we need to hold objects, under what circumstances should we give priority to arrays, and under what circumstances should we give priority to containers?
In the initial version of Java, fixed-size arrays were absolutely necessary, not only because the Java designers chose to include primitive types in Java and some performance-based considerations, but also because the initial version has very little support for containers. Therefore, in early versions of Java, it was always reasonable to choose to include arrays, specifically in the following three aspects:
Efficiency
In Java, Arrays are the most efficient way to store and randomly access object referencessequences. An array is a simple linear sequence, which makes element access very fast. However, The price paid for this speed is that the size of the array object is fixed and cannot be changed during its lifecycle. Because ArrayList can realize automatic allocation of space and is more flexible, we should usually prefer ArrayList to array, but this flexibility requires overhead. Therefore, ArrayList is much less efficient than arrays.
Type
Before JDK 1.5, Java did not introduce generics. Therefore, when container classes before generics handle objects, they will treat them as having no specific type, that is, these objects will be treated as Object. The reason why arrays are better than containers before generics is that you can create an array to hold a specific type. This means you can prevent incorrect types from being inserted and inappropriate types extracted through compile-time type checking. Of course, Java will prevent you from sending inappropriate messages to objects, both at compile time and at runtime. Therefore, it is not that which method is less safe, but it will be more elegant if errors can be pointed out during compilation.
The ability to save basic types
Arrays can hold basic types, but containers before generics cannot.
After JDK 1.5, Java introduced generics and automatic packaging mechanisms (generics can ensure the generation of type-safe containers, and automatic packaging mechanisms enable containers to hold basic types ), which makes today's containers dwarf arrays in every aspect except performance. In addition, generics are a great threat to arrays, and usually, the two cannot be combined well(Arrays with parameterized types cannot be instantiated) .
Therefore, when we use recent Java versionsprogramming, Containers should be preferred over arrays. We should refactor a program to use arrays only if performance has proven to be an issue and switching to arrays will help performance.
1. Array basics
The array identifier is just a reference , pointing to a real object created in the heap. This object is used to save references to other objects or values of basic types;
Object arrays save references, and basic type arrays directly Save basic type values;
The "[ ]" syntax is the only way to access array objects;
2. Create and Initialization
Implicitly created as part of array initialization
String[] strs = { ... }; // 创建方式 1 --- 花括号内对象的个数就是数组大小System.out.println(strs.length); // 输出 0
Create explicitly using new Expression
String[] strs = new String[5]; //创建方式 2String[] ss = new String[]{ ... }; //创建方式 3
The essence of multidimensional array: The elements of an array are still arrays
// 创建方式 1int[][] a = { { 1, 2, 3, }, { 4, 5, 6, }, }; // 创建方式 2int[][][] a = new int[2][2][4];//粗糙数组:每个向量具有任意长度Random rand = new Random(47); // 3-D array with varied-length vectors: int[][][] a = new int[rand.nextInt(7)][][]; for(int i = 0; i < a.length; i++) { a[i] = new int[rand.nextInt(5)][]; for(int j = 0; j < a[i].length; j++) a[i][j] = new int[rand.nextInt(5)]; }
Arrays and generics cannot be combined well, that is to say, arrays with parameterized types cannot be instantiated;
T[] first = new T[3]; // ERROR A<String>[] arrays = new A<String>[4]; // ERROR: Cannot create a generic array of A<String>
Can create a generic array reference;
A<String>[] arrays; // OK
Arrays are covariant;
Object[] objs = new String[3]; // OK
In short, Generic containers are always a better choice than generic arrays.
1. The concept of variable parameter types
Java SE5 adds variable parameter types (Variable Argument Type), in the form of "Type... args", can only be used as method parameters. The variable parameter list is suitable for situations where the number of parameters is uncertain but the type is certain (java treats variable parameters as an array). Special attention should be paid to the fact that the variable parameter list must be in the last item (that is, only one variable parameter is supported at most). When there is more than one variable parameter list, one of the variables must not be the last item, so only one variable parameter is supported. Because the number of parameters in the variable parameter list is uncertain, when there are parameters of the same type behind it, Java cannot distinguish whether the passed parameter belongs to the previous variable parameter or the following parameter, so it can only place the variable parameter at the end. One item.
// 代码示例public class TestVarArgus { public static void dealArray(int... intArray){ for (int i : intArray) System.out.print(i +" "); System.out.println(); } public static void main(String args[]){ dealArray(); dealArray(1); dealArray(1, 2, 3); } }/* Output: 1 1 2 3 *///:~
The variable parameter list has the following characteristics:
can only appear at the end of the method parameter list;
… is located in variabletype and variable name, with or without spaces before and after;
When calling the method with variable parameters, the compiler will Variable parameters implicitly create an array, so we can access the variable parameter list in the form of an array in the method body(The compiler treats the variable parameters as an array).
2. Compatibility of variable parameter types and arrays
The compiler considers the array type and the variable parameter type to be the same, that is, they cannot be overloaded;
public class TestVarArgus { public static void dealArray(int... intArray){ for (int i : intArray) System.out.print(i +" "); System.out.println(); } //ERROR : Duplicate method dealArray(int[]) in type TestVarArgus public static void dealArray(int[] intArray){ for (int i : intArray) System.out.print(i +" "); System.out.println(); } public static void main(String args[]){ dealArray(); dealArray(1); dealArray(1, 2, 3); } }
Variable parameters are compatible with array type parameters, but array type parameters are not compatible with variable parameters;
// 代码示例 1 : 给参数为可变参数类型的方法传递数组public class TestVarArgus { public static void dealArray(int... intArray){ for (int i : intArray) System.out.print(i +" "); System.out.println(); } public static void main(String args[]){ int[] intArray = {1, 2, 3}; dealArray(intArray); // OK } }
// 代码示例 2 : 给参数为数组类型的方法传递可变参数public class TestVarArgus { public static void dealArray(int[] intArray){ for (int i : intArray) System.out.print(i +" "); System.out.println(); } public static void main(String args[]){ dealArray(1, 2, 3); // ERROR } }
In fact, for sample code 2, you only need a method defined as dealArray(int, int, int) or a method defined as dealArray(int...). Therefore, it is naturally impossible to match the dealArray(int[]) method with array type parameters.
Parameter matching principle: if it can match fixed-length methods, then will be given priority matching This method;
public class TestVarArgus { //含有不定参数的那个重载方法是最后被选中的public static void dealArray(int... intArray){ System.out.println("Bad"); } public static void dealArray(int count, int count2){ System.out.println("Bingo"); } public static void main(String args[]){ dealArray(1, 2); } } /* Output: Bingo *///:~
##Even the parameters of the main function that we are familiar with can also be rewritten into the form of variable parameter type: public static void main(String... args) .##
Function | Introduction | Note |
---|---|---|
System.arraycopy( Object src, int srcPos, Object dest, int destPos, int length) | From the specified source array Copy an array, copying starts from the specified position and ends at the specified position of the target array | If you copy an object array, only the reference to the object is copied, not the copy of the object itself (shallow copy);This method will not perform automatic packaging and automatic unpacking, so the two arrays must have the same exact type; Must explicitly create a new array object as a copy |
Copy the specified array, | intercept or use null Filling | The underlying call is System.arraycopy; returns a new array object. If the length of the new array exceeds the length of the original array, Then keep the default value of the array |
The above is the detailed content of Summary of Java Array Code Examples. For more information, please follow other related articles on the PHP Chinese website!