Detailed Java high quality code array and collection _java

Source: Internet
Author: User
Tags array length data structures shallow copy

1. Performance considerations, Priority selection Array

Arrays are used less frequently in project development, especially in the business-oriented development, the first array has no list,set and other sets of methods, to find an increase algorithm to write their own, extremely cumbersome trouble, but because of list,set, such as the use of generic support, storage for the packaging class, Arrays can use basic data types, while performing operations with basic data types are much faster than wrapper types, and the bottom of the collection class is implemented through arrays.

2. Use variable-length arrays if necessary

In the Learning Collection class, many people like to take the fixed length of the array and set the type of the length of the self to do comparisons, but in fact, this comparison is not appropriate, through the observation of the collection class such as the implementation of ArrayList can actually see that the so-called collection of the longer, in fact, only in a roundabout way to expand

  

Copy Code code as follows:

public static t[] Expandcapacity (t[] data, int newlength) {

Determine if the value is negative

Newlength = newlength < 0? 0:newlength;

Generate a new array, copy the original value and set the length

return arrays.copyof (data, newlength);

}


When performance requirements are high, consider using arrays for encapsulation, and the length of the array is not an excuse to not use them.

3. Beware of shallow copies of arrays

A shallow copy of an array is also based on Java programming, when a shallow copy is an array copy, the base type copies the value, and the reference type copies the reference address, in the example above, the copy array uses the arrays.copyof as a shallow copy, which requires attention when used

4. Specify the initial capacity for the collection in a clear scenario

In our usual use, because the collection type is automatically long, the basic creation of the object does not attach an initial value to the collection class, and take our most commonly used ArrayList to illustrate that, first of all, when the collection capacity reaches the critical point, the underlying array is copyof. The new array is generated, the new array is 1.5 times times the size of the old array, and the default array length is 10, and when we know exactly how much data to put into the container, we should indicate the initial value and avoid the performance overhead caused by multiple use of copyof

5. Select the appropriate maximum value algorithm

For the data to find the maximum or minimum value, which is the most basic data structure knowledge, in Java, we also have many ways to implement, the following list of 2 algorithms

  

Copy Code code as follows:

public static int Getmaxbyarray (int[] data) {

The simplest way to find your own implementation

int max = data[0];

for (int i = 1, size = Data.length i < size; i++) {

max = Max < I? I:max;

}

return Max;

}


Copy Code code as follows:

public static int Getmaxbyarray (int[] data) {

Sort first to get the last bit

Arrays.sort (data);

return data[data.length-1];

}


6. Basic type array Conversion traps!

Please observe the following code

Copy Code code as follows:

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 size of the output is 1 at this time

}


The result we expect is to convert the elements of the array through arrays.aslist into the collection class, but instead, we just added the array itself to the entry and did not split the values in the array, so if you add generics to the collection list, you'll get the wrong hints during compilation. or change the array itself to integer to solve the problem

The list object produced by the 7.asList method cannot be changed

With the example above, we can see that using the Arrays.aslist method to convert an array to a list, what is the special of the list returned by the Aslist method? Note that this returned list does not support changes because the Aslist method returns the It's not java.util.ArrayList, but a static private inner class in the arrays tool class that has the same parent class Abstractlist as ArrayList, but when it comes to the method of replication Add, But it throws out the unsupportedoperationexception, this static private inner class only implements the Size,toarray,get,contains methods

8. Use different traversal methods for different data structures

Please view the following code

Copy Code code as follows:

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

}

The following is how the LinkedList collection is traversed

List LinkedList = new LinkedList ();

for (Integer integer:linkedlist) {

}

}


Why do I have to choose a different way of traversal for LinkedList and ArrayList?

1. Because the ArrayList implements the Ramdomaccess interface (random access interface), the Ramdomaccess interface and the Serializable,cloneable interface are the interface in Java, which means that this class can be accessed randomly. For ArrayList, there is no correlation between the data, that is, the adjacent two positions are not dependent on each other, can be accessed randomly,

The foreach syntax in 2.Java is the iterator (iterator) Variant usage, we know that iterators are one of 23 design patterns, but iterators need to know the relationship of two element time, otherwise how to provide hasnext support? It is because the last element is determined to determine whether the next element exists, forcibly establishing the relationship, violating the special ArrayList random access

3. In LinkedList, because it is stored in the form of a two-way linked list, the support for iterators is very good, because the linkedlist adjacent two elements are inherently related so in the LinkedList and ArrayList to take a different way of traversal, If the reader is interested in taking the form of a linkedlist, you will find that there is a big gap between the efficiency of the two.

8. Choose ArrayList or LinkedList in a timely manner

The main differences between ArrayList and LinkedList:

1.ArrayList the underlying data structure is an array, while the linkedlist underlying structure is a two-way list

2. When inserting data, because ArrayList need to postpone the array element to the position after each insert, and LinkedList only need to change the head node and the tail node to complete the insert operation, so the insertion operation is more frequent, the priority is to use LinkedList

3. When deleting data, because ArrayList to maintain the order of the array, when the element needs to be deleted backwards or forwards, and linkedlist or change the end-tail node.

4. In the update, because LinkedList will use binary traversal of the way to find positioning elements to update, compared to ArrayList direct positioning subscript element replacement, ArrayList more efficient for the update

5.LinkedList can simulate the queue, through the operation of LinkedList Addfirst,addlast, etc.

9. List equality just care about element data

Java for our ease of programming for LIST,SET,MAP interface, so the Equlas in the collection class, so that we compare the equality of two sets, we need to compare the equality of the elements data, avoid the wrong Java code due to the substitution set implementation class

Copy Code code as follows:

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

Do not care about the specific implementation, the output is true

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.