Collection Summary of Java

Source: Internet
Author: User

Collection

Derived from the Java.util package, is a very useful and commonly used data structure!!!!! It literally means a container. The specific inheritance implementation relationship, such as the overall impression, followed by the introduction of the various parts of the method, considerations, and application scenarios.

--------------------------------------------------------------------------------------------

Collection Main methods:

Boolean Add (Object o) to the collection
Boolean remove (object o) deletes the specified object
int size () returns the number of elements in the current collection
Boolean contains (object O) finds whether the specified object is in the collection
Boolean IsEmpty () determines whether the collection is empty
Iterator Iterator () returns an iterator
Boolean containsall (Collection C) finds whether the collection has elements in the collection C
Boolean AddAll (Collection c) adds all elements of collection C to the collection
void Clear () deletes all elements in the collection
void RemoveAll (Collection c) removes elements from the collection that are also in the C collection
void Retainall (Collection c) removes elements not contained in collection C from the collection
--------------------------------------------------------------------------------------------

Collection primary sub-interface objects:

├list (Abstract interface, repeatable order)

List Main methods:
void Add (int index,object Element) Adds an object at the specified position
Boolean addall (int index,collection c) adds the elements of the collection C to the specified location
Object get (int index) returns the element at the specified position in the list
an int indexOf (Object o) returns the position of the first occurrence of the element O.
Object Remove (int index) deletes the element at the specified position
The Object set (int index,object element) replaces the element on position index with element elements, returning the substituted element
void sort ()
--------------------------------------------------------------------------------------------

1.List Primary sub-interface object

│├linkedlist No synchronization method


│├arraylist Non-synchronous (unsynchronized)


│└vector (synchronous) is very similar to ArrayList, but vectors are synchronous

└stack remembers the push and pop methods, and the Peek method gets the top element of the stack, the empty method tests if the stack is empty, and the search method detects the position of an element on the stack. Note: Stack is empty when it is first created.

--------------------------------------------------------------------------------------------
2.└set does not contain duplicate elements
HashSet
Sortset
TreeSet

In addition:-queue (inheriting collection)---Deque
--------------------------------------------------------------------------------------------

3.Map

Map does not inherit the collection interface, and map provides a key-to-value mapping.

Method:

Boolean equals (Object O) Comparison object
Boolean remove (Object o)
Put (Object key,object value) add key and value

├hashtable any non-empty (Non-null) object. Synchronization of

├hashmap an empty object. Not synchronized, but high efficiency, more commonly used. Note: The iteration sub-operation time overhead is proportional to the capacity of the HashMap. Therefore, if the performance of the iterative operation is quite important, do not set the initialization capacity of the hashmap too high or load factor too low.
└weakhashmap improved HashMap, which implements a "weak reference" to key, which can be recycled by GC if a key is no longer referenced externally.
Sortmap---TreeMap

4. Summary:
A. If you are involved in a stack, queue (advanced post-out) and so on, you should consider using the list, for the need to quickly insert, delete elements, should use LinkedList, if you need to quickly randomly access elements, you should use ArrayList.

B. If the program is in a single-threaded environment, or if access is done only in one thread, it is more efficient to consider non-synchronous classes, and if multiple threads may operate on a class at the same time, the synchronized classes should be used.

C. Pay special attention to the operation of the hash table, and the object as key should correctly replicate the Equals and Hashcode methods .


D. Try to return the interface instead of the actual type, such as returning a list instead of ArrayList, so that if you need to change ArrayList to LinkedList later, the client-side code does not have to be changed. This is for abstract programming.


E.arraylist, Hashset/linkedhashset, Priorityqueue, LinkedList are thread insecure,

You can use the Synchronized keyword, or a workaround like the following:


[Java]View PlainCopy
    1. List List = Collections.synchronizedlist (new ArrayList (...));



5. Several interview FAQs:

What is the difference between 1.q:arraylist and vectors? What's the difference between HashMap and Hashtable?

A:vector and Hashtable are thread-synchronized (synchronized). In performance, ArrayList and HashMap are better than vectors and Hashtable respectively.


2.Q: Roughly explaining the architecture of the Java collection
A:list, set, and map are the main three interfaces in this set system.
Where list and set inherit from the collection interface.
Set does not allow elements to be duplicated. HashSet and TreeSet are the two main implementation classes.
The list is ordered and allows elements to be duplicated. ArrayList, LinkedList, and vectors are the three main implementation classes.
The map also belongs to the collection system, but differs from the collection interface. A map is a collection of key pairs of value, where the key column is a collection. Key cannot be duplicated, but value can be repeated. HashMap, TreeMap, and Hashtable are the three main implementation classes.
The SortedSet and SortedMap interfaces sort the elements by the specified rules, sortedmap the key column.


3.q:comparable and Comparator differences
A: When you call the Java.util.Collections.sort list method to sort, the object in the list must implement the comparable interface.
Java.util.Collections.sort (List list,comparator c), you can temporarily declare a Comparator to implement sorting.

[Java]View PlainCopy
  1. Collections.sort (ImageList, new Comparator () {
  2. public int Compare (object A, object B) {
  3. int ordera = Integer.parseint ((Image) a). Getsequence ());
  4. int orderb = Integer.parseint ((Image) b). Getsequence ());
  5. return ordera-orderb;
  6. }
  7. });



If you need to change the sorting order
Change to return Orderb-ordera.

6. Other points of attention

The list interface is a simple extension of collection, and its concrete implementation classes are often ArrayList and LinkedList. You can put anything in a list container and take it out when you need it. ArrayList can be seen in its name as an array-like form of storage, so its random access speed is very fast, and LinkedList's internal implementation is a linked list, it is suitable for in the middle of the list of links need to frequently insert and delete operations. The application can be freely selected as needed. The iterator can only walk forward through the container, while Listiterator inherits the iterator idea and provides a way to iterate through the list.


The set interface is also an extension of collection, and unlike list, the object element in set cannot be duplicated, meaning you cannot put the same thing two times into the same set container. Its commonly used concrete implementation has hashset and TreeSet class. HashSet can quickly locate an element, but the object you put into HashSet needs to implement the Hashcode () method, which uses the algorithm of the previously mentioned hash code. And TreeSet will put the elements in order to store, which requires you to put the object is sortable, which is used in the collection framework provided by the other two practical classes comparable and comparator. A class is sortable, and it should implement the comparable interface. Sometimes more than one class has the same sorting algorithm, it is not necessary to define the same sorting algorithm at each separate time, as long as the comparator interface is implemented. There are two useful common classes in the collection framework: collections and Arrays. Collections provides some very useful methods for a collection container such as sorting, copying, finding, and populating, and arrays is doing a similar operation on an array.


A map is a container that associates a key object with a value object, and a value object can be a map, and so on, so that a multilevel map can be formed. For a key object, like set, a key object in a map container does not allow repetition, which is to keep the consistency of the search results, and if there are two key objects, then you have a problem with the value object that the key object has, and you may not get the value object you want, and the result will be confusing. So the uniqueness of the key is very important, and it conforms to the nature of the set. Of course, in the process of use, the value object corresponding to a key may change, then the last modified value object corresponds to the key. There is no unique requirement for value objects. You can map any number of keys to a value object without any problems (though it may be inconvenient for you to use it, you don't know what you get is the value object for that key). There are two more common implementations of map: HashMap and TreeMap. HashMap also uses the hash code algorithm, in order to quickly find a key, TreeMap is the key in order to store, so it has some extension methods, such as Firstkey (), Lastkey () and so on, you can also specify a range from the TreeMap to get its child map. The association of Keys and values is simple, with the pub (Object Key,object value) method to associate a key with a value object. Use Get (object key) to get the value object corresponding to this key object.



How to traverse a map:

a.//the most conventional kind of traversal method, the most common is the most commonly used, although not complex, but very important, this is the most familiar to us, not much to say!!

[Java]View PlainCopy
  1. Public static void work (map<string, student> Map) {
  2. collection<student> C = map.values ();
  3. Iterator it = C.iterator ();
  4. For (; It.hasnext ();) {    
  5. System.out.println (It.next ());
  6. }
  7. }



b.//uses keyset to traverse, its advantage is that you can get the values you want based on the key value you want, more flexibility!!

[Java]View PlainCopy
  1. Public static void Workbykeyset (map<string, student> Map) {
  2. set<string> key = Map.keyset ();
  3. For (Iterator it = Key.iterator (); It.hasnext ();) {    
  4. string s = (string) it.next ();
  5. System.out.println (Map.get (s));
  6. }
  7. }




c.//a more complicated kind of traversal here, violence!!, it's too flexible to get anything you want.

[Java]View PlainCopy
  1. Public static void Workbyentry (map<string, student> Map) {
  2. Set<map.entry<string, student>> set = Map.entryset ();
  3. for (iterator<map.entry<string, student>> it = Set.iterator (); it
  4. . Hasnext ();) {
  5. map.entry<string, student> Entry = (map.entry<string, student>) it
  6. . Next ();
  7. System.out.println (Entry.getkey () + "+" + entry.getvalue ());
  8. }
  9. }




Another concise notation for d.//map.entry (foreach traversal mode)

[Java]View PlainCopy
  1. Public static void Workbyentry (map<string, student> Map) {
  2. Set<map.entry<string, student>> set = Map.entryset ();
  3. for (map.entry<string, student> me:set) {
  4. System.out.println (Me.getkey () + "+" + me.getvalue ());
  5. }
  6. }


7.Queue

There are two differences between a queue and a list:

The former has the concept of "team head", taking elements, removing elements, all for the "Team Head" operation (usually but not always FIFO, that is, first-out),

      While the latter must be guaranteed at the end of the insert, the former provides two methods for some of the same operations on elements, throwing exceptions/returns special Values--add ()/offer (), remove ()/poll (), Element ()/peek (). It is not difficult to think that in the so-called two methods, the method of throwing the anomaly can be achieved by wrapping the method of not throwing the exception, which is what Abstractqueue did.


The Deque interface inherits the queue, but it has no relationship with Abstractqueue. Deque also provides an insert and delete operation at the head and tail of the team.

Priorityqueue

The priorityqueue is used to hold the elements that contain precedence, and the inserted objects must be comparable. An array is also encapsulated inside the class. Unlike the abstract parent class Abstractqueue, Priorityqueue's offer () method throws a null pointer exception when inserting NULL--null is not a priority in the usual sense of comparison with other elements; In addition, the Add () method is directly wrapping the offer () , there is no additional behavior.
Because its internal data structure is the reason of the array, many operations need to first convert the elements through indexof () to the corresponding array subscript, and then further operations, such as remove (), Removeeq (), contains () and so on. In fact, this array to maintain the priority queue way, is the use of heap (heap), the specific can refer to any of the algorithm books, such as "Introduction to the algorithm," and so on, here does not expand the explanation. is related to the properties of the heap, which must be traversed from beginning to the other when looking for the specified element, rather than using a binary lookup.

LinkedList


LinkedList is both a list and a queue (Deque) because it is bidirectional, and the inner element (Entry) retains a reference to the previous and next elements. You can get a trailing reference by using the header of the header and taking its previous. With this transformation, it is easy to implement the behavior required by deque. It is therefore possible to support the behavior of stacks, which are inherently push () and Pop () methods. In short, it is a doubly linked list in Java, which supports operations like normal doubly linked lists.
Unlike arrays, when a particular element is looked up according to the subscript, it can only be traversed to obtain it, and thus is less efficient than ArrayList at random access. Nevertheless, the author has made the best use of LinkedList's features to optimize the site, minimizing the number of visits:

[Java]View PlainCopy
  1. Private entry<e> Entry (int index) {
  2. if (Index < 0 | | | index >= size)
  3. throw New Indexoutofboundsexception ("Index:" +index+
  4. ", Size:" +size);
  5. entry<e> E = header;
  6. if (Index < (size >> 1)) {
  7. For (int i = 0; i <= index; i++)
  8. e = E.next;
  9. } Else {
  10. For (int i = size; i > Index; i--)
  11. e = e.previous;
  12. }
  13. return e;
  14. }


LinkedList supports both header and trailing inserts, but the add () method inherited from the collection interface is inserted at the tail.

Collection Summary of 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.