List a few common questions about Java collections and give answers

Source: Internet
Author: User
Tags addall

1. When to use LinkedList, when to use ArrayList?

ArrayListis a list implemented using an array, which is essentially an array. An element in the ArrayList can be randomly fetched by an index. However, if the array is full, the time complexity of O (n) is required when new elements are added and a new array is assigned and the elements of the original array are moved past. Adding or removing an element requires moving other elements in the array. This is the biggest drawback of ArrayList.

LinkedListis a doubly linked list. Therefore, when you need to get an element in the list, you need to traverse the list from beginning to end. On the other hand, adding or removing elements in a linked list quickly requires only the time complexity of O (1). Spatially, a node in a linked list requires two additional pointers to its previous and next nodes.

Summarize:

In terms of time complexity , if the list is added or removed more, priority is given to linkedlist; If the query operation is more, the ArrayList is preferred.

In terms of space complexity , LinkedList will occupy more space.

2. How to remove elements from collection while traversing edges

The only correct way to modify collection while traversing edges is Iterator.remove() to use the method, as follows:

12345 Iterator<Integer> it = list.iterator();while(it.hasNext()){    // do something    it.remove();}

One of the most common error codes is as follows:

123 for(Integer i : list){    list.remove(i)}

Running the above error code will report an ConcurrentModificationException exception. This is because when using foreach (for an Integer i:list) statement, a iterator is automatically generated to traverse the list, but the list is being Iterator.remove() modified. In Java, one thread is generally not allowed to traverse collection while another thread modifies it.

3. How do I convert a list to int[]?

Many people may think that it's just a matter List.toArray() of use. The List.toarray () method can only get integer[] and cannot get int[].

The simplest way to do this is to use the Apache Commons Lang library ArrayUtils .

1 int[] array = ArrayUtils.toPrimitive(list.toArray(newInteger[0]));

There are no shortcuts in the JDK. It is important to note that it cannot be used directly List.toArray() because it translates the list into integer[] instead of int[]. The correct approach is as follows:

1234 int[] array = newint<div class="list "></div>;for(inti = 0; i < list.size(); i++){    array[i] = list.get(i);}
4. How do I convert int[] into a list?

Ibid., many people think that just use Arrays.asList() can, it is not. Because int[] cannot be used as a parameter to the method, it can only be integer[].

The Arrays.asList() following features are available for the method:

    • 1. This method is not good for arrays of basic data types and is not recommended when the array is the base data type
    • 2. When using the Aslist () method, the array is linked to the list. When one of them is updated, the other automatically gets the update. Because the list actually referenced by the aslist is the array Note: The basic data type array does not have this attribute only for object array types.
    • The 3.asList gets the array without the add and remove methods. Because the list returned by Aslist is an inner class in arrays, the class does not define the add and remove methods.

So how do you convert int[] into a list?

You have to do it yourself:

12345 int [] array = { 1 Code class= "Java plain", 2 3 4 , 5 }; list<integer> List = new arraylist<integer> (); for ( int i:array) { &NBSP;&NBSP; list.add (i);
5. What is the best way to filter a collection?

such as filtering out an integer greater than 5 in the list.

1234567 Iterator<Integer> it = list.iterator();while(it.hasNext()){    inti = it.next();    if(i > 5) {  //过滤掉大于5的整数        it.remove();     }}
6. What is the simplest way to convert a list to set?

There are two methods, depending on how you want to define two elements equal. The first method is to put the list HashSet in, and whether the method elements are equal is compared by their hashcode (). If you need to define your own method of comparison, you need to use it TreeSet .

1 Set<Integer> set = newHashSet<Integer>(list);
12 Set<Integer> set = newTreeSet<Integer>(aComparator);set.addAll(list);
7. How do I delete the duplicate elements in ArrayList?

If you don't care about the order of elements in ArrayList, you can drop the list into the set to remove the repeating element and then put it back in the list.

123 Set<Integer> set = newHashSet<Integer>(list);list.clear();list.addAll(set);

If you care about the order of elements in ArrayList, you can use them LinkedHashSet .

8. Orderly Collection

There are many ways to maintain a collection order in Java. Some need to implement comparable interface, some need to specify their own comparator.

    1. Collections.sort()Can be used to sort the list. This sort is stable and can guarantee the performance of Nlog (n).
    2. PriorityQueueProvides a sorted queue. PriorityQueue Collections.sort() The difference is that the PriorityQueue dynamic maintenance of an ordered queue (which is reordered for each element added or removed), but only the header elements in the queue.
    3. If there are no duplicate elements in the collection, TreeSet it is another option. The PriorityQueue same is true for TreeSet dynamic maintenance of an ordered set. TreeSetthe largest and smallest elements can be obtained from.

Summary: Collections.sort() provides a list that is sorted once. PriorityQueueand TreeSet Dynamic maintenance of the ordered collection.

9. Copy List

There are two ways to copy a list. One is to use a ArrayList constructor.

1 ArrayList<Integer> dstList = newArrayList<Integer>(srcList);

The other is to use Collections.copy() .

12 ArrayList<Integer> dstList = newArrayList<Integer>(srcList.size());Collections.copy(dstList, srcList);

It is important to note that the target list is at least as long as the source list length when using this method. Otherwise, an IndexOutOfBoundsException exception is reported.

There are two additional points to note:

    1. Both methods are shallow copies of
    2. Collections.copy()The two parameters of the method must be list, and the method ArrayList parameter is collection, so the ArrayList method is more general.

List a few common questions about Java collections and give answers

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.