Details arrays and collections of JAVA quality code

  • 2020-04-01 02:13:34
  • OfStack

1. Performance considerations, choose the array first

Array in the using frequency of project development is less and less, especially in business is given priority to the development of the first array without the List, Set collection provides many methods, such as, increase lookup algorithm is to write your own, extremely tedious trouble, but as a result of the List, the Set after collection use generics support, storage for the wrapper classes, and array is a basic data types can be used, and using the basic data type of execution speed is much faster than the packing type, but the bottom of the collection classes is implemented through the array.

2. If necessary, use variable-length arrays

In the learning collection class, many people like to compare the fixed length of the array with the variable length of the collection type, but in fact, this comparison is not appropriate. By observing the implementation of the collection class such as ArrayList, it can be seen that the so-called set length is actually used to expand the original array in a indirect way


  public static T[] expandCapacity(T[] data, int newLength) {
  //Determine if it is negative
  newLength = newLength < 0 ? 0 : newLength;
  //Generate a new array, copy the original values, and specify the length
  return Arrays.copyOf(data, newLength);
  }
 

When performance requirements are high, consider using arrays for encapsulation. The constant length of arrays is no excuse for not using them

Beware of shallow copies of arrays

The shallow copyOf the array is also the foundation of the foundation in Java programming. The shallow copy is when the array is copied, the basic type copies the value, and the reference type copies the reference address

4. Specify the initial capacity for the collection in an explicit scenario

In our normal use, because the collection type is automatically variable-length, so basic not for collection classes to create objects with an initial value, and then take our most commonly used ArrayList to illustrate, we first need to know, when the collection capacity reached a tipping point, will be at the bottom of the array copyOf operations, generate a new array, and the new array capacity is 1.5 times of the old array, and the default array length of 10, when we clearly know to be put into the container in the data quantity is large, should specify the initial value, avoid using copyOf multiple performance overhead

5. Select the appropriate maximum algorithm

The maximum or minimum value of the data search, this is the most basic knowledge of the data structure, in Java we also have a lot of ways to implement, the following two algorithms are listed


  public static int getMaxByArray(int[] data) {
  //The simplest self-implemented lookup method
  int max = data[0];
  for (int i = 1, size = data.length; i < size; i++) {
  max = max < i ? i : max;
  }
  return max;
  }


  public static int getMaxByArray(int[] data) {
  //Sort first and get the last bit
  Arrays.sort(data);
  return data[data.length - 1];
  }

6. Basic types of array conversion trap!

Observe the following code


  public static void main(String[] args) {
  int[] nums = new int[] { 1, 2, 3, 4, 5 };
  List list = Arrays.asList(nums);
  System.out.println(list.size());
  //The output size is 1
  }

We expect as a result of the elements in the array by Arrays. The asList transition to the collection classes, but instead, we only will be added into the array itself, not the values within the array split apart, as if to more generic collections List will give at compile time error prompt, or will change into an Integer array itself can solve the problem

7. The List object generated by the asList method cannot be changed

From the above example, we can see that using the arrays.aslist method can transform an array into a List, so what's so special about the List returned by the asList method? Note that the returned List is does not support the change, the reason is because asList () method returns, not Java. Util. ArrayList, but Arrays in a static class private inner class, although has the same realization and ArrayList parent class AbstractList, but in autotype the methods such as add, but throw UnsupportedOperationException, only the private static inner class size, toArray, get, contai ns

8. Use different traversal methods for different data structures

Watch the following code


  public static void main(String[] args) {
  //The following is how the ArrayList collection is traversed
  int num = 80 * 10000;
  List arrayList = new ArrayList(num);
  for (int i = 0, size = arrayList.size(); i < size; i++) {
  arrayList.get(i);
  }
  //Here is how the LinkedList collection is traversed
  List linkedList = new LinkedList();
  for (Integer integer : linkedList) {
  }
  }

Why choose different traversals for LinkedList and ArrayList?

1. Because ArrayList implements RamdomAccess interface (random access interface),RamdomAccess interface and Serializable,Cloneable interface are the marking interface in Java, representing that this class can be accessed randomly. For ArrayList, it indicates that there is no correlation between data, that is, two adjacent locations have no interdependent relationship, and can be accessed randomly.

2. The foreach syntax in Java is the deformation usage of iterator(iterator). We know that iterator is one of the 23 design patterns, but iterator needs to know the relationship between two element time. It is because the previous element has to determine whether the next element exists that this relationship is forced to be established, in violation of the special nature of ArrayList random access

3. In the LinkedList, for it is through the form of two-way linked list to store, so the support of the iterator is very good, because LinkedList neighboring relationship between two elements there is originally so on LinkedList and should take different way of traversing the ArrayList and readers if you are interested in can try to LinkedList USES the subscript in the form of access, will find that the efficiency has a larger gap

8. Choose an ArrayList or LinkedList when appropriate

The main differences between ArrayList and LinkedList:

1. The underlying data structure of ArrayList is an array, while the underlying structure of LinkedList is a two-way LinkedList

2. When inserting data, since ArrayList needs to move the array elements backward after each insertion, and LinkedList only needs to change the header and tail nodes to complete the insertion operation, LinkedList is preferred when insertion operations are frequent

3. When deleting data, LinkedList still changes the header and footer nodes, since the ArrayList keeps the array in order and the elements need to be moved backward or forward after the deletion.

4. During the update, since LinkedList will search for locating elements and update them by half-iterating,ArrayList is more efficient for the update than ArrayList, which directly locates subscript elements

5.LinkedList can simulate the queue through addFirst,addLast and other operations of LinkedList

9. Equal lists only care about element data

Java in order to we can safely face the List,Set,Map and other interfaces for programming, so the collection class in the equlas carbon, let us compare the two sets are equal, just need to compare the element data is equal, to avoid errors caused by the replacement of the collection implementation class Java code


  public static void main(String[] args) {
  List arrayList = new ArrayList();
  arrayList.add(1);
  arrayList.add(2);
  List linkedList = new LinkedList();
  linkedList.add(1);
  linkedList.add(2);
  System.out.println(arrayList.equals(linkedList));
  //Regardless of the implementation, the output is true
  }


Related articles: