JAVA Collection Framework

Source: Internet
Author: User
Tags bitset map class

Before Java 2, Java provided the ad hoc class. For example: Dictionary, Vector, Stack, and properties These classes are used to store and manipulate groups of objects.

Although these classes are useful, they lack a central, unified theme. For this reason, the way you use the vector class differs greatly from the way you use the Properties class.

The collection framework is designed to meet several goals.

    • The framework must be high-performance. The implementation of the basic set (dynamic array, linked list, tree, hash table) must also be efficient.
    • The framework allows different types of collections to work in a similar way, with a high degree of interoperability.
    • The expansion and adaptation of a set must be simple.

To do this, the entire collection framework is designed around a standard set of interfaces. You can use the standard implementations of these interfaces directly, such as LinkedList, HashSet, and TreeSet, and you can implement your own collections via these interfaces.

A collection Framework is a unified schema used to represent and manipulate collections. All the collection frameworks include the following:

    • interface: is an abstract data type that represents a collection. The interface allows the collection to manipulate the details of its representatives independently. In object-oriented languages, interfaces usually form a hierarchy.
    • implementation (Class): is the specific implementation of the collection interface. Essentially, they are reusable data structures.
    • algorithm: is a useful calculation for the execution of methods in an object that implements a collection interface, for example: Search and sort. These algorithms are called polymorphic, because the same approach can have different implementations on similar interfaces.

In addition to the collection, the framework also defines several map interfaces and classes. A key/value pair is stored in the map. Although maps are not collections, they are fully integrated in the collection.

Set Frame System

The Java Collection Framework provides a set of well-performing, easy-to-use interfaces and classes, and the Java Collection framework is located in the Java.util package, so a guide is required when using the collection framework.

Collection interface

The collection framework defines some interfaces. This section provides an overview of each interface:

the difference between set and list
    • 1. The set interface instance stores unordered, non-repeating data. The list interface intern stores the elements that are ordered and can be duplicated.

    • 2. Set retrieval efficiency is low, delete and insert efficiency is high, insert and delete do not cause element position change < implement class has hashset,treeset>.

    • 3. Lists and arrays are similar, and can grow dynamically, automatically increasing the length of the list based on the length of the actual data stored. find element Efficient, insert delete inefficient because it causes other elements to change position The < implementation class has arraylist,linkedlist,vector> .

Collection Implementation Class (Collection Class)

Java provides a set of standard collection classes that implement the collection interface. Some of these are concrete classes that can be used directly, while others are abstract classes that provide partial implementations of the interface.

The standard collection classes are summarized in the following table:

Serial Number class Description
1 Abstractcollection
Most of the collection interfaces are implemented.
2 Abstractlist
Inherits from Abstractcollection and implements most of the list interfaces.
3 abstractsequentiallist 
inherits from Abstractlist, providing chained access to data elements rather than random access.
4 linkedlist

The class implements the list interface, which allows null (empty) elements. Mainly used to create a linked list data structure, this class does not have a synchronization method, if more than one thread colleague access a list, you must implement the access synchronization itself, the solution is to create a list when a synchronous list is constructed. For example:

 Listlist=collections.newlinkedlist (...));     
5 ArrayList

The class also implements the list interface, implements a variable-sized array, and provides better performance when randomly accessing and traversing elements. This class is also unsynchronized and should not be used in multi-threaded situations. This class is expanded by the way the raw capacity *3/2+1, which is the automatic growth length.

6 Abstractset
Inherits from Abstractcollection and implements most of the set interfaces.
7 HashSet

The class implements the set interface, does not allow duplicate elements, does not guarantee the order of elements in the collection, and allows elements with a value of NULL, but only one at most.

8 Linkedhashset
A hash table and a link list implementation of a Set interface with predictable iteration order.
9 TreeSet

This class implements a set interface, which enables sorting and other functions.

10 Abstractmap
Most of the map interfaces are implemented.
11 HashMap
HashMap is a hash table that stores content that is a key-value pair (key-value) mapping.
This class implements the map interface, stores the data according to the hashcode value of the key, has a fast access speed, allows a record's key to be null, and does not support thread synchronization.
12 TreeMap
Inherits the Abstractmap, and uses a tree.
13 Weakhashmap
Inherits the Abstractmap class, using the weak key hash table.
14 Linkedhashmap
Inherit from HashMap, ordering elements in the natural order of the elements.
15 Identityhashmap
Inherits the Abstractmap class, which uses reference equality when comparing documents.

The classes defined in the Java.util package have been discussed in the previous tutorial as follows:

Serial Number class Description
1 Vector

This class is very similar to ArrayList, but the class is synchronous and can be used in multi-threaded situations, which allow the default growth length to be set by default, which is twice times the original.

2 Stack
A stack is a subclass of a vector that implements a standard LIFO stack.
3 Dictionary
The Dictionary class is an abstract class used to store key/value pairs, similar in function to the map class.
4 Hashtable

This class implements the class map interface, similar to HashMap, where a key or value is allowed to be null to support thread synchronization, so it is slower to write.

5 Properties
Properties inherit from Hashtable. Represents a persisted set of properties. Each key and its corresponding value in the attribute list is a string.
6 BitSet
A Bitset class creates a special type of array to hold the bit values. The array size in the bitset is incremented as needed.

A Bitset class creates a special type of array to hold the bit values. The array size in the bitset is incremented as needed.

Set algorithm

The collection framework defines several algorithms that can be used for collections and mappings. These algorithms are defined as static methods of the collection class.

Some methods can throw classcastexception exceptions when trying to compare incompatible types. Throws an unsupportedoperationexception exception when attempting to modify a non-modifiable collection.

A collection defines three static variables: Empty_set empty_list,empty_map. None of these variables can be changed.

Serial Number Algorithm Description
1 Collection algorithms
Here is the implementation of all the algorithms in a list.

How to use iterators

Typically, you would want to iterate through the elements in a collection. For example, displays each element in the collection.

The general traversal array is either a for loop or an enhanced for, and these two methods can also be used in the collection framework, but there is also a way to iterate through the collection framework, which is an object that implements the iterator interface or the Listiterator interface.

An iterator that enables you to iterate through the elements of the collection or delete them. Listiterator inherits the iterator to allow bidirectional traversal of the list and modify the elements.

All the methods provided by the iterator and Listiterator interfaces are listed here by example.

Traverse ArrayList

public class test{public static void Main (string[] args) {     list<string> list=new arraylist<string> (); C1/>list.add ("Hello");     List.add ("World");     List.add ("Hahahaha");     The first traversal method uses foreach to traverse list for     (String str:list) {            ///can also overwrite for (int i=0;i<list.size (); i++) This form        System.out.println (str);     }      The second kind of traversal, the linked list into the array related content to traverse     string[] strarray=new string[list.size ()];     List.toarray (Strarray);     for (int i=0;i<strarray.length;i++)//This can also be rewritten as a  foreach (String str:strarray) Form     {        System.out.println (Strarray[i]);     }         The third traversal uses iterators to carry out related traversal          iterator<string> ite=list.iterator ();     while (Ite.hasnext ())//After judging the next element there is a value     {         System.out.println (Ite.next ());}}}     

Analytical:

Three methods are used to traverse the ArrayList collection, and the third approach is to use an iterator, which does not have to worry about exceeding the length of the collection during the traversal.

Traverse Map
public class test{public static void Main (string[] args) {map<string, string> Map = new hashmap<string      , string> ();      Map.put ("1", "value1");      Map.put ("2", "value2");            Map.put ("3", "Value3");      First: Universally used, two times value System.out.println ("Traverse key and value by Map.keyset");      For (String Key:map.keySet ()) {System.out.println ("key=" + key + "and value=" + map.get (key));      }//second type of SYSTEM.OUT.PRINTLN ("Traverse key and value by Map.entryset using iterator");      Iterator<map.entry<string, string>> it = Map.entryset (). Iterator ();       while (It.hasnext ()) {map.entry<string, string> Entry = It.next ();      System.out.println ("key=" + entry.getkey () + "and value=" + entry.getvalue ());      }//Third type: recommended, especially when the capacity is large System.out.println ("Traverse key and value through Map.entryset"); For (map.entry<string, string> entry:map.entrySet ()) {System.out.println ("key=" + entry.getkey () + "and V Alue= "+ Entry.getvaLue ());      }//Fourth type SYSTEM.OUT.PRINTLN ("Traverse all the value through Map.values (), but cannot traverse key");      For (String v:map.values ()) {System.out.println ("value=" + V); }     }}

  

JAVA Collection Framework

Related Article

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.