Various collection problems in Java

Source: Internet
Author: User

One, Java type collection diagram

interface of the Collection interface collection of objects

--list Sub-interfaces are ordered and repeatable

--linkedlist interface Implementation Class List insert Delete no synchronization thread unsafe

--arraylist interface Implementation class array random access no synchronization thread insecure

--vector interface implements class array synchronization thread safety

--stack

--set sub-interfaces are only received once, and do internal sorting is not repeatable

--hashset

--linkedhashset

--treeset

A collection of MAP interface key-value pairs

--hashtable interface Implementation class synchronization thread safety can not store null values

--hashmap interface Implementation Class No synchronization thread is unsafe can store null values

--linkedhashmap

--weakhashmap

--treemap

--identifyhashmap

Map uses hash hashes to find elements faster than ArrayList

Second, Detailed introduction

1. List interface

The 1.1 order is the most important feature of the list and is able to access the elements with the index, allowing the same elements to be used;

1.2 In addition to the collection Interface Prerequisite iterator () method, List provides a listiterator () method that allows the addition of deletions, set elements, and forward-backward traversal;

  LinkedList: Sequential access is optimized for relatively slow random access

1.3 LinkedList allows null values, provides AddFirst (), GetFirst () and other methods at the header or tail of the linkedlist, so that the LinkedList can be used as a stack, queue, or bidirectional queue;

1.4 LinkedList There is no synchronization method, if you have multi-threaded access, you must implement access synchronization yourself

such as List list=collection.synchronizedlist (new LinkedList (...));

  ArrayList: Inserts and removes elements in the middle of the list is slow and random access is relatively fast

1.5 ArrayList has an array implementation that allows all elements, including null

1.6 Listiterator should only be used to traverse the ArrayList from the back forward, rather than to insert and remove elements. Because that is much more expensive than linkedlist.

  Vector:

1.7 The Iterator created by the vector is created and is being used, and the other thread changes the state of the vector, at which point the Iterator method is called to throw concurrentmodificationexception, so the exception must be caught

  Stack:

1.8 implements a last-in-first-out stack, and the stack provides 5 additional ways to make the Vector available as a stack. The basic push and pop methods, and the Peek method to get the stack top element, the empty method tests if the stack is empty, and the search method detects the position of an element on the stack. Stack has just been created empty stack;

2 SET interface

The 2.1 set does not guarantee that the order of elements is maintained and that there is at most one null value;

The constructor of the 2.2 set has a constraint, and the incoming collection parameter cannot contain duplicate elements;

HashSet:

Linkedhashset:

TreeSet:

3.Map interface

3.1 You can use ContainsKey () and Containsvalue () to test if a map contains a "key" or "value", with a built-in sort;

3.2 Hsahmap uses the object's Hashcode () for quick querying, and "hash code" is a "relatively unique" int value that represents an object, which is generated by converting some information of the object, and all Java objects can produce a hash code because hashcode () Is the method defined in the base class Object;

  HashTable:

3.3 Implements a Key-value mapped hash table, any non-empty object can be a key or value;

3.4 Add data put, remove data get;

3.5 Hashtable adjusts performance by initializing the capacity (initial capacity) and load factor (load factor) two parameters, usually by default load factor 0.75 to achieve a better balance of time and space. Increasing the load factor can save space but the corresponding lookup time will increase, which will affect operations such as get and put;

3.6 An object that is a key will determine the location of the corresponding value by calculating the hash function, so any object that is a key must implement the Hashcode method and the Equals method. The Hashcode method and the Equals method inherit from the root class Object, and if you use a custom class as a key, be very careful, according to the hash function definition, if two objects are the same, namely Obj1.equals (OBJ2) =true, then their hashcode must be Must be the same, but if two objects are different, their hashcode is not necessarily different, if two different objects hashcode the same, this phenomenon is called conflict, the conflict will cause the operation of the hash table time overhead increases, so as far as possible to define a good hashcode () method, can speed up the operation of the hash table;

  HASHMAP:

3.7 HashMap non-synchronous, allows null values. When HASHMAP is treated as Collection (the values () method can return Collection), the cost of inserting and querying "key-value pairs" is fixed, but its iteration-time overhead is proportional to the capacity of HashMap. Therefore, if the performance of the iterative operation is quite important, do not set the HASHMAP initialization capacity (initial capacity) too high, or the load factor (load factor) is too low;

  Linkedhashmap

3.8 is similar to HashMap, but when iterating through it, the order in which key-value pairs are obtained is either their insertion order or the least recently used (LRU) order. Just a little slower than HashMap. It is faster when iterating, because it uses the list to maintain the internal order;

  Weakhashmap:

3.9 Weak key (weak key) Map is an improved HASHMAP, which is designed to solve a particular problem, a "weak reference" to key, if a key is no longer referenced externally (no Map outside the reference), then the key can be garbage collector (GC Recycling

  TreeMap:

Based on the implementation of red-black tree data structure. When you look at key or key-value pairs, they are sorted (the order is determined by Comparabel or Comparator). TreeMap is characterized by the fact that the results you get are sorted. TreeMap is the only Map with the SubMap () method, which can return a subtree;

  Identifyhashmap:

Use = = instead of equals () to compare the "key" to the hash map. Designed to solve special problems.

Three comparisons

1. Array array class (Arrays)

1.1 Java storage and random access to a series of objects, the array is the most efficient, but the disadvantage is that the capacity is fixed and cannot be changed dynamically, can not determine the actual number of elements, length is the capacity;

1.2 Array classes specialize in manipulating arrays, and array classes have a set of static functions: Equals (), fill (), sort (), BinarySearch () finds elements in a sorted array, system.arraycopy () array copies;

1.3 If you do not know how many objects to write the program, you need to automatically expand capacity when the space is insufficient, you need to use the Container class library, array is not used;

2. Containers (Collection) and map

2.1 Collection has only one element per position; Map holds key-value pairs, like a small database (Collections.max (Collection coll); Take the largest element in Coll);

Iv. Summary

1 List,set,map will hold objects as object type;

2 Collection, List, Set, and Map are interfaces and cannot be instantiated. The ArrayList, vectors, HashTable, and HashMap, which inherit from them, are like class, which can be instantiated;

3 Extract the key sequence using keyset () to generate a set (non-repeatable) for all keys in the map;

Extracts the value sequence using values (), generating a Collection for all values in the map;

4 in various Lists, for the need to quickly insert, delete elements, you should use LinkedList (available linkedlist to construct stack stacks, queue queues), if you need to quickly randomly access elements, you should use ArrayList. The best practice is to use ArrayList as the default choice. Vector is always slower than ArrayList, so try to avoid it.

5 in various sets, HashSet is usually better than hashtree (INSERT, find). Use TreeSet only if you need to produce a sorted sequence. The only reason for the existence of Hashtree: the ability to maintain the ordering state of its elements; HashMap for quick lookups in various Maps

6 when the number of elements is fixed, use array, because the array efficiency is the highest

Original: http://blog.csdn.net/jackie03/article/details/7312481

Various collection problems in Java

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.