[Simple Java] the 10 most common problems in Java collections, simplejava

Source: Internet
Author: User

[Simple Java] the 10 most common problems in Java collections, simplejava

The following are some Java set-related questions that are frequently asked on Stackoverflow. Before reading these questions, you 'd better go to [Simple Java] Java Collection framework interface and class hierarchy structure.

When should I prioritize the role list instead of the ArrayList?

ArrayList is essentially an array, and its elements can be accessed directly through indexes. However, when the array is full, it takes O (n) Time to apply for a new and larger array space and copy all elements to the new array. In addition, inserting and deleting elements requires moving other elements in the array, which may be the biggest disadvantage of ArrayList.

The linked list is a two-way linked list. Therefore, when accessing the elements in the linked list, it needs to start searching from the head node of the linked list. But on the one hand, for insert and delete operations, the sort list is relatively faster, because it only needs to change the local location of the linked list.

In general, in the worst case, the time complexity of the two is compared 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)

In addition to the running time, the use of memory space should also be considered, especially for large lists. In the explain list, each node requires two additional pointers to the forward and back nodes. However, ArrayList only needs an array for storing elements.

For more information about the comparison between other lists, see [Simple Java] ArrayList vs sort List vs Vector.

When traversing the set iteratively, the elements are deleted correctly.

When iterating a set, the only correct method to modify the set is to use the Iterator. remove () method, as shown in the following example:

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

In addition, a common error code is as follows:

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

Run the preceding error code and you will get a ConcurrentModificationException. This is because the code above generates an iterator (generated by the for statement) to traverse the list, the list has been modified (through Iterator. remove ()). In Java, a thread does not allow another thread to modify the set during iterative collection traversal.

How to convert List to int []

The simplest method is to use the ArrayUtils tool class under the Apache Commons Lang library, as follows:

int[] array = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));

In JDK, there is no shortcut to perform the above conversion. Note that you cannot use the List. toArray () method, because this will convert the List to Integer []. The correct method is as follows:

int[] array = new int[list.size()];for(int i=0; i < list.size(); i++) {    array[i] = list.get(i);}
How to convert int [] to List

The simplest method is to use the ArrayUtils tool class of Apache Commons Lang, as follows:

List list = Arrays.asList(ArrayUtils.toObject(array));

There are still no shortcuts in JDK. You can only use the following methods:

int[] array = {1,2,3,4,5};List<Integer> list = new ArrayList<Integer>();for(int i: array) {    list.add(i);}
What is the best way to filter a set?

Similarly, you can use third-party libraries such as google's Guava library or Apache Commons Lang to implement this function. Both provide filter () method (Guava's Collections2 or Apache's CollectionUtils class ). The filter () method returns matched elements.

In JDK, this will become difficult. The good news is that the Predicate interface is added in java 8 to implement this function. But now, we can only use the iterator to traverse the entire set:

Iterator<Integer> itr = list.iterator();while(itr.hasNext()) {    int i = itr.next();    if (i > 5) { // filter all ints bigger than 5        itr.remove();    }}

Of course, you can imitate the Guava or Apache operation method and introduce a new interface Predicate. This may be something that senior developers will do, as shown below:

public interface Predicate<T> {    boolean test(T o);}public static <T> void filter(Collection<T> collection, Predicate<T> predicate) {    if ((collection != null) && (predicate != null)) {        Iterator<T> itr = collection.iterator();        while(itr.hasNext()) {            T obj = itr.next();            if (!predicate.test(obj)) {                itr.remove();            }        }    }}

Then, we use the following code to filter the set:

filter(list, new Predicate<Integer>() {    public boolean test(Integer i) {        return i <= 5;    }});
The simplest way to convert List to Set

There are two ways to implement this function, depending on how you define "equal ". The first method stores a list into a HashSet. the repetition of elements is primarily distinguished by hashCode (). In most cases, this is feasible. However, if you need to define an equal comparison method, you 'd better use the second method to define your own comparator.

Set<Integer> set = new HashSet<Integer>(list);
Set<Integer> set = new TreeSet<Integer>(aComparator);set.addAll(list);
Deleting duplicate elements in ArrayList

This problem is very similar to the previous one. If you don't care about the order of the elements in ArrayList, a clever way is to save the list elements to the set to remove repeated elements, then, the elements of the set are moved back to the List. The following code:

ArrayList** list = ... // initial a list with duplicate elementsSet<Integer> set = new HashSet<Integer>(list);list.clear();list.addAll(set);

If you are concerned about the sequence of elements, you can use the javashashset in the standard JDK to implement this function.

Sort a set

In Java, there are several ways to maintain the order of elements in the set. They provide the default sorting order or sort by specifying the comparator. However, even for the default sorting, any element in the set must implement the Comparable interface.

  • The Collections. sort () method can sort a List set. As described in javadoc, This sorting method is stable and can ensure the sorting performance isN log (n).
  • PriorityQueue is an ordered queue with Collections. the difference between sort () is that the PriorityQueue queue is always ordered, but you can only access the first and end of the queue, and cannot access elements immediately, such as PriorityQueue. get (4.
  • If there are no repeated elements in the collection, TreeSet is another option. Like PriorityQueue, it maintains the order of elements. You can directly obtain the first and last elements in the TreeSet, but you still cannot access the elements in the Set immediately.

In short, Collections. sort () provides a one-time sorting of the List. PriorityQueue and TreeSet can maintain the order of elements in the set, but cannot access the elements immediately.

The difference between Collections. emptyList () and direct new instance

This problem also applies to emptyMap () and emptySet ().

Both methods return an empty set, but Collections. emptyList () returns an immutable set, meaning you cannot add elements to this empty set. In fact, each call to Collections. emptyList () does not create an empty set, but reuse an existing empty set instance. If you are familiar with the singleton mode, you should know what I said. If you call it frequently, this will provide better performance.

Collections. copy method

There are two ways to copy a List set to another List set, one of which is to use the ArrayList constructor, as shown below:

ArrayList<Integer> dstList = new ArrayList<Integer>(srcList);

The other is to use the Collections. copy () method (as shown below). Note that in the first row, we allocated an initial capacity equal to the length of the source List set.

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

What are the differences between the two methods?

  • First, when the target set does not have enough space to store elements in the source set, the Collections. copy () method does not resize the target set. It throws an IndexOutOfBoundsException exception.
  • The parameter type of Collections. copy () can only be the implementation class of the List interface. The ArrayList constructor can accept the implementation class of the Collection interface as the input parameter, so it is more common.

 

Http://www.programcreek.com/2013/09/top-10-questions-for-java-collections/.

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.