Top 10 questions about Java collections

Source: Internet
Author: User
Tags addall

Top 10 questions about Java collections
The following are the most discussed questions about the Java set in stackoverflow.
1. About LinkList and ArrayListArrayList: the internal implementation is an array, and the elements can be obtained through index. However, if an array is full, we must reassign a larger array and move all elements to the new array. the time complexity is O (n ). When adding or deleting an element, you also need to move other elements in the array. This is the disadvantage of ArrayList. Linked List: A two-way linked list. Therefore, if we want to obtain the intermediate element, we need to traverse from the beginning. On the other hand, it is very easy to add or delete an element, because we only need to operate on the linked list itself. In general, the time complexity comparison between the two is as follows:

                   | Arraylist | LinkedList ------------------------------------------ get(index)        |    O(1)   |   O(n) add(E)            |    O(n)   |   O(1) add(E, index)     |    O(n)   |   O(n) remove(index)     |    O(n)   |   O(n) Iterator.remove() |    O(n)   |   O(1) Iterator.add(E)   |    O(n)   |   O(1)
Besides considering the time complexity, when the List is large, the space complexity cannot be ignored:
LinkList: each node also requires two additional pointers, respectively, to the forward node and the next node ArrayList: Only one array needs more comparison information...

2. The most effective way to remove set ElementsThe only correct way to remove a set element is to use the Iterator. remove () method:
Iterator
 
   itr = list.iterator();while(itr.hasNext()) {   // do something   itr.remove();}
 
 
The following processing method is incorrect and an exception is reported: ConcurrentModificationException
for(Integer i: list) {  list.remove(i);}
3. How to convert a List into an int [] array?
The simplest way is to use ArrayUtils under the Apache Commons Lang Toolkit:
int[] array = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));
If jdk is used, there is no shortcut. Note that we cannot use the List. toArray () method, because the result is Integer []. The correct method should be:
int[] array = new int[list.size()];for(int i=0; i < list.size(); i++) {  array[i] = list.get(i);}
4. How to convert int [] to List?
Similar to the above, we can use the ArrayUtils tool class:
List list = Arrays.asList(ArrayUtils.toObject(array));
Or there are still no shortcuts:
int[] array = {1,2,3,4,5};List
  
    list = new ArrayList
   
    ();for(int i: array) {  list.add(i);}
   
  
5. What is the best way to filter a set?
Of course, the most convenient and best way is to use third-party jar packages, such as Guava or Apache Commons Lang, both of which provide the filter () method. In jdk, the process becomes less simple (but Java 8 already supports Predicate). However, before Java 8, we usually need to traverse all the elements in the Set:
Iterator
   
     itr = list.iterator();while(itr.hasNext()) {   int i = itr.next();   if (i > 5) { // filter all ints bigger than 5      itr.remove();   }}
   
However, we can simulate Guava and Apache Commons Lang and introduce a new Predicate interface, which is the method of many senior engineers:
public interface Predicate
  
    {   boolean test(T o);} public static 
   
     void filter(Collection
    
      collection, Predicate
     
       predicate) {    if ((collection != null) && (predicate != null)) {       Iterator
      
        itr = collection.iterator();          while(itr.hasNext()) {            T obj = itr.next();            if (!predicate.test(obj)) {               itr.remove();            }        }    }}
      
     
    
   
  
filter(list, new Predicate
  
   () {    public boolean test(Integer i) {        return i <= 5;     }});
  
6. There are two simplest ways to convert a List to a Set:
Set
  
    set = new HashSet
   
    (list);
   
  
Set
  
    set = new TreeSet
   
    (aComparator);set.addAll(list);
   
  
7. How to remove repeated elements from ArrayList
Similar to the above method, if you do not care about the sequence:
ArrayList** list = ... // initial a list with duplicate elementsSet
  
    set = new HashSet
   
    (list);list.clear();list.addAll(set);
   
  
If you are concerned about the sequence, replace the above HashSet with the sequence HashSet.
8. Sort the set    
There are many ways to sort a set
1. Collections. sort (): sort
2. PriorityQueue: the queue sequence is always maintained, but elements can only be obtained from the queue header.
3. TreeSet: always keep the queue order, and the elements are not repeated. You can get the elements from the top or bottom, but cannot get them randomly.
9.Collections.emptyList() vs new Instance     
Both of the above methods will return an empty List, but Collections. the List returned by emptyList () is immutable. Each method call will not re-create an instance, but reuse the original Instance (that is, the singleton mode), so the efficiency will be higher.
10.Collections.copy     
There are two ways to copy a List. The first one is:
ArrayList
  
    dstList = new ArrayList
   
    (srcList);
   
  
The second method is to use the Collections. copy () method:
ArrayList
  
    dstList = new ArrayList
   
    (srcList.size());Collections.copy(dstList, srcList);
   
  
What is the difference between the two?
If the target set (dstList) is smaller than the source set, using Collections. copy () will throw IndexOutOfBoundsException. What are the advantages of this function? First, it ensures that the running efficiency is linearly related to the set size, and second, it can realize the reuse of the set.

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.