Java collections comparison summary

List, Set, Map, and the difference between the three summary

  • List: order to deal with a good helper

    List storing a set of interfaces are not unique (there may be multiple elements reference the same object), the object orderly
  • Set: pay attention to the unique nature

    Collection does not allow duplicate. There will be no more elements refer to the same object.

  • Key experts use to search for: Map

    Use key-value pair storage. Map will maintain and Key associated value. Key two can reference the same object, but can not repeat Key, typically of type String Key, but may be any object.

Arraylist and LinkedList difference

Arraylist bottom using an array (memory read data high efficiency, low insertion position delete specific efficiency), the bottom of the LinkedList using two-way circular linked list data structure (insert, delete particularly efficient). After this course learned data structure linked list stored we know, insert, delete elements from the time complexity of impact positions of the elements, are approximations O (1) and the array is approximately O (n), particularly so when the data and suggested the use of LinkedList when often need to insert delete elements. general procedure only Arraylist enough, because in general the amount of data is not very big, Arraylist is the most used collection classes.

ArrayList and Vector difference

All methods of the Vector class are synchronized. By the two threads can safely access a Vector object, but one thread to access Vector
, to spend a lot of time codes on the synchronization operation. Arraylist not synchronized, it is recommended that when not in use synchronous Arraylist.

The difference between HashMap and Hashtable

  1. HashMap is not thread-safe, HashTable are thread-safe; internal HashTable basic methods have been synchronized modification.

  2. Because the thread safety problems, HashMap HashTable efficient than a little, HashTable basically been eliminated.
  3. There HashMap allows null values, whereas in the HashTable put into the key as long as there is a null, a NullPointerException is thrown directly.

Hashtable and HashMap There are several major differences: thread safety and speed. Hashtable used only when you need the full thread-safe, but if you use Java5 or more, please use it ConcurrentHashMap

HashSet and HashMap difference

HashSet and HashMap difference

The difference between HashMap and ConcurrentHashMap

The difference between HashMap and ConcurrentHashMap

  1. ConcurrentHashMap the entire tub segmentation array segment (Segment), and are protected by a lock latch on each segment with respect to the HashTable synchronized lock granularity finer some better concurrency, but no lock HashMap mechanism, not thread safe. (After JDK1.8 ConcurrentHashMap enabled a new way to achieve using CAS algorithm.)
  2. HashMap of key-value pairs allow null, but ConCurrentHashMap are not allowed.

How to check for duplicate HashSet

When you join the objects HashSet, HashSet will first calculate the hashcode value of the object to determine the position of the object added, will also be compared with other hashcode value added objects, if there is no match of hashcode, HashSet assumes that the object is not repeated . But if the object has the same hashcode value found, then we will call equals () method to check whether the object really equal hashcode same. If they are the same, HashSet will not let join a successful operation. (Excerpt from my book Java enlightenment "Head fist java" second edition)

hashCode () and equals () the relevant provisions:

  1. If two objects are equal, it must also be the same hashcode
  2. Two equal objects, the method returns true equals two
  3. Hashcode two objects have the same value, they are not necessarily equal
  4. In summary, equals overridden the method, the method must be covered hashCode
  5. The default behavior hashCode () is to create a unique value to objects on the heap. If no override hashCode (), then the two objects are not equal class anyway (even if these two objects point to the same data).

== and equals the difference

  1. == two variables are determined or examples are not directed to the same memory space equals the value of two variables are determined or examples points to the memory space is not the same
  2. == refers to the memory address comparing equals () is compared to the contents of the string 3 == refers to whether the same reference equals () refers to the values ​​are identical

The difference between comparable and comparator

  • by the interface actually comparable java.lang package which has a compareTo (Object obj) method is used to sort
  • a comparator that is from the fact that it has a packet java.util compare (Object obj1, Object obj2) method is used to sort

Generally we need to use a set of custom ordering, we will compare override compareTo method or methods, if we need to implement two set a certain sort, such as a song title and object respectively a singer name Ranking methods, we can override the compareTo methods and use of homemade Comparator Comparator method to achieve two or song name and singer name sort sort behalf of our second edition of the only two parameters Collections.sort () .

Comparator custom sorting

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class CollectionsSort {

    public static void main(String[] args) {

        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(-1);
        arrayList.add(3);
        arrayList.add(3);
        arrayList.add(-5);
        arrayList.add(7);
        arrayList.add(4);
        arrayList.add(-9);
        arrayList.add(-7);
        System.out.println("原始数组:");
        System.out.println(arrayList);
        // void reverse(List list):反转
        Collections.reverse(arrayList);
        System.out.println("Collections.reverse(arrayList):");
        System.out.println(arrayList);
/*      
         * void rotate(List list, int distance),旋转。
         * 当distance为正数时,将list后distance个元素整体移到前面。当distance为负数时,将
         * list的前distance个元素整体移到后面。
         
        Collections.rotate(arrayList, 4);
        System.out.println("Collections.rotate(arrayList, 4):");
        System.out.println(arrayList);*/
        
        // void sort(List list),按自然排序的升序排序
        Collections.sort(arrayList);
        System.out.println("Collections.sort(arrayList):");
        System.out.println(arrayList);

        // void shuffle(List list),随机排序
        Collections.shuffle(arrayList);
        System.out.println("Collections.shuffle(arrayList):");
        System.out.println(arrayList);

        // 定制排序的用法
        Collections.sort(arrayList, new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        System.out.println("定制排序后:");
        System.out.println(arrayList);
    }

}

Override the compareTo method implementation to sort by age

package map;

import java.util.Set;
import java.util.TreeMap;

public class TreeMap2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeMap<Person, String> pdata = new TreeMap<Person, String>();
        pdata.put(new Person("张三", 30), "zhangsan");
        pdata.put(new Person("李四", 20), "lisi");
        pdata.put(new Person("王五", 10), "wangwu");
        pdata.put(new Person("小红", 5), "xiaohong");
        // 得到key的值的同时得到key所对应的值
        Set<Person> keys = pdata.keySet();
        for (Person key : keys) {
            System.out.println(key.getAge() + "-" + key.getName());

        }
    }
}

// person对象没有实现Comparable接口,所以必须实现,这样才不会出错,才可以使treemap中的数据按顺序排列
// 前面一个例子的String类已经默认实现了Comparable接口,详细可以查看String类的API文档,另外其他
// 像Integer类等都已经实现了Comparable接口,所以不需要另外实现了

class Person implements Comparable<Person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    /**
     * TODO重写compareTo方法实现按年龄来排序
     */
    @Override
    public int compareTo(Person o) {
        // TODO Auto-generated method stub
        if (this.age > o.getAge()) {
            return 1;
        } else if (this.age < o.getAge()) {
            return -1;
        }
        return age;
    }
}

How to sort the list of Object

  • Sort an array of objects, we can use Arrays.sort () method
  • A collection of objects to be sorted, require the use of the Collections.sort () method

How to achieve conversion of the array and List

List switch array: toArray (arraylist.size () method; array to a List: Arrays of asList (a) Method

List<String> arrayList = new ArrayList<String>();
        arrayList.add("s");
        arrayList.add("e");
        arrayList.add("n");
        /**
         * ArrayList转数组
         */
        int size=arrayList.size();
        String[] a = arrayList.toArray(new String[size]);
        //输出第二个元素
        System.out.println(a[1]);//结果:e
        //输出整个数组
        System.out.println(Arrays.toString(a));//结果:[s, e, n]
        /**
         * 数组转list
         */
        List<String> list=Arrays.asList(a);
        /**
         * list转Arraylist
         */
        List<String> arrayList2 = new ArrayList<String>();
        arrayList2.addAll(list);
        System.out.println(list);

How intersection of ArrayList collection of union and set difference set to repeat

List need to use several methods defined in the interface:

  • addAll (Collection <extends E?> c): the order specified set Iterator returned to the set of all of the elements of this list is added to the end of the
    example code:
  • retainAll (Collection c <?>): Retains only the elements in this list contained in the specified collection.
  • removeAll (Collection c <?>): removed from the list of all the elements contained in the specified collection.
package list;

import java.util.ArrayList;
import java.util.List;

public class MethodDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Integer> list1 = new ArrayList<Integer>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);

        List<Integer> list2 = new ArrayList<Integer>();
        list2.add(2);
        list2.add(3);
        list2.add(4);
        list2.add(5);
        // 并集
        // list1.addAll(list2);
        // 交集
        //list1.retainAll(list2);
        // 差集
        // list1.removeAll(list2);
        // 无重复并集
        list2.removeAll(list1);
        list1.addAll(list2);
        for (Integer i : list1) {
            System.out.println(i);
        }
    }

}

HashMap works and code implementation

Collections Framework source code learning HashMap (JDK1.8)

ConcurrentHashMap works and code implementation

ConcurrentHashMap the principle and source code analysis

A set of underlying data structures summarized frame

- Collection

1. List

  • Arraylist: Array (fast queries, additions and deletions slow thread-safe, high efficiency)
  • Vector: Array (fast queries, additions and deletions slow thread-safe, low efficiency)
  • LinkedList: list (slow queries, additions and deletions fast thread-safe, high efficiency)

2. Set

  • HashSet (unordered only): Set a hash table or called hash (hash table)
  • LinkedHashSet: linked lists and hash tables. Sort the list by the guarantee element, the only evidence of a hash table of elements
  • TreeSet (order only): red-black tree (sort of self-balancing binary tree.)

- Map

  • HashMap: Map interface based on the hash table (hash key of the hash table, Map structure is a mapping table stored key-value pair)
  • LinkedHashMap: add a linked list data structure on the basis of HashMap
  • HashTable: hash table
  • TreeMap: red-black tree (self-balancing binary tree sort)

Selection collection

According to the main feature set to choose, for example, we need to key on the selection of the collection at getting to the Map interface element values, need to sort the choice TreeMap, when it does not need to sort selection HashMap, the need to ensure the security thread on the selection ConcurrentHashMap. When we only need to be stored element value, you select the collection implement collection interface, you need to ensure that the only element to achieve the set when selecting the Set interface such as TreeSet or a HashSet, you do not need to choose, such as ArrayList or LinkedList implement the List interface, and then implement them in accordance with It features a collection of interfaces to choose.

Guess you like

Origin www.cnblogs.com/scholar-hwg/p/12131563.html