Home >Java >javaTutorial >Summary of Java Array Code Examples

Summary of Java Array Code Examples

黄舟
黄舟Original
2017-03-14 11:54:041558browse


Abstract

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.


1. Key pointsOverview

  • Arrays and containers

  • Creation and creation of arrays Initialization

  • Arrays and generics

  • Arrays and variable parameter lists

  • Arrays tool class Practical functions

  • Summary


2. Arrays and containers

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.


3. Creation and initialization of arrays

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
String[] strs = new String[5];  
//创建方式 2String[] ss = new String[]{ ... };   
//创建方式 3

3. Multidimensional array

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

4. Arrays and generics

  • 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.


5. Arrays and variable parameter types

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 
    *///:~

6. Practical functions of Arrays tool class

1. Copy array

##copyOf(T[] original, int newLength)Copy the specified array,

 
注意:

 对于以上两个方法:

  • 若复制对象数组,那么只是复制了对象的引用,而不是对象本身的拷贝;

  • 这两个方法不会执行自动包装和自动拆包,所以两个数组必须具有相同的确切类型。


2、数组的字符串方式表示

方法: Arrays.toString(Object[] a) / Arrays.deepToString(Object[] a)

作用: 返回指定数组内容的字符串表示形式:前者适用于一维数组,或者适用于多维数组


3、数组的比较

方法: Arrays.equals(Object[] a, Object[] a2)  /   deepEquals(Object[] a1, Object[] a2) (多维)

作用: 比较两个数组:元素类型相同,元素个数相等,对应位置的元素相同;

注意:

  • 通过对每个元素使用 equals() 作比较来判断;

  • 对于基本类型,使用的是基本类型的包装器类的 equals() 方法(对于 int 类型使用 Integer.equals() 作比较);

  • 使用 equals() 方法比较原则:是不是同一个对象,是不是同一个类型,是不是具有相同的内容。

int[] a1 = new int[10]; 
int[] a2 = new int[10]; 
Arrays.fill(a1, 47); 
Arrays.fill(a2, 47); 
print(Arrays.equals(a1, a2));    //true

4、数组的排序

  使用内置的排序方法,就可以对任意的基本类型数组排序;也可以对任意的对象数组进行排序,只要该对象实现了 Comparable 接口或具有相关联的 Comparator (独立的实现该接口的类)。

方法: Arrays.sort(Object[] a) / Arrays.sort(Object[] a, int fromIndex, int toIndex)  
   Arrays.sort(T[] a, Comparatorafdb413486077de11f19a9eac0d8049c c) / Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator117c5a0bdb71ea9a9d0c2b99b03abe3e c)

作用: 对数组内元素进行升序排序 (默认)

String[] sa = Generated.array(new String[20], new RandomGenerator.String(5)); 

// 利用 String 内置的比较器(已实现 Comparable 接口):字典序(大写字母开头的词都放在前面输出,之后才是小写字母开头的词)Arrays.sort(sa);   
// ... ,WHkjU, YNzbr, bkIna, cQrGs, ....
// 利用 Comparator 比较 : Collections.reverseOrder() : 现有顺序的逆序Arrays.sort(sa, Collections.reverseOrder()); 

// 利用 Comparator 比较 : String.CASE_INSENSITIVE_ORDER : 忽略大小写将单词一起进行排序Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);

  Java 标准类库中的排序算法针对正排序的特殊类型进行了优化 ———— 针对基本类型设计的“快排” 和 针对对象设计的“稳定归并排序”。所以,无需担心排序的性能,除非你可以证明排序部分的确是程序效率的瓶颈。


5、在已排序的数组中查找

  若数组已经 排好序,就可以使用该方法执行快速查找;若对未排序的数组使用该方法,将产生不可预料的结果。

方法: binarySearch(Object[] a, Object key) / binarySearch(T[] a, T key, Comparator117c5a0bdb71ea9a9d0c2b99b03abe3e c)

作用: 使用 二分搜索来搜索指定数组,以获得指定对象。在进行此调用之前,必须根据元素的自然顺序对数组进升序排序(通过 sort(Object[]) 方法); 使用二分搜索法来搜索指定数组,以获得指定对象。在进行此调用之前,必须根据指定的比较器(通过 sort(T[], Comparator) 方法)对数组进行多态升序排序

注意:

  • 已经有序 的数组进行查找;

  • If the target is found, the value returned by the method is not less than 0; otherwise, the negative return value it generates indicates the position that should be inserted under this sorting;

  • "sort(Object[])" corresponds to "binarySearch(Object[] a, Object key)", "sort(T[], Comparator)" corresponds to binarySearch(T[] a, T key, Comparator117c5a0bdb71ea9a9d0c2b99b03abe3e c) Corresponds.

     If the array contains duplicate elements, this method cannot guarantee which element is found; if you need to sort an array without duplicate elements, you can use Tree Set(maintain sorting order) or LinkedHashSet(maintain insertion order) to sort. There is no need to maintain arrays yourself unless they become a bottleneck in your program.


6. Fill array

Method: fill(Object[] a, Object val)
Function: You can only use the same value to fill each position, and for objects, it is to copy the reference of the same object to fill it


7. Conversion between arrays and containers

Method: asList(T... a)
Function: Returns a Fixed size list supported by the specified array
Note:

  • The resulting List is fixed size because The underlying representation is the array, so it cannot be resized. Therefore, calling the add/remove method will throw java.lang.UnsupportedOperationException (optional operation).

  • So, Arrays.asList() is really all about: passing its result as a constructor argument to any Collection (or using addAll method, Collections.addAll staticmethod), this can generate a dynamic container.


## 7. Summary

Principle:

  • Prefer to use containers instead of arrays;

  • Use arrays and variable parameters When making method parameters, prioritizing the use of variable parameters will make the program more decoupled;

  • The practical functions of the Arrays tool class will make us Get twice the result with half the effort in programming.

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
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn