Java Basics--java Collection Framework

Source: Internet
Author: User
Tags bitset map class

Java Collection Framework 1, overview:

  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.

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.

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.

2. Set interface

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

Serial Number Interface Description
1 Collection interface

Collection is the most basic set interface, and a Collection represents a group of Object,java that do not provide classes that inherit directly from Collection, providing only inherited Yu interfaces (such as list and set).

2 List interface

The list interface is an ordered collection that allows you to precisely control where each element is inserted, and to access the elements in the list by index (where the element is positioned in the list, like an array's small tag).

And the same elements are allowed.

3 Set

The set has exactly the same interface as the Collection, except that the set does not hold duplicate elements, but behaves differently.

4 SortedSet
Inherit from set that holds an ordered collection.
5 Map
Maps a unique key to a value.
6 Map.entry
Describes an element in a map (a key/value pair). is the inner class of a map.
7 SortedMap
Inherit from map so that key remains in ascending order.
8 Enumeration
This is a traditional interface and a defined method through which you can enumerate (get one at a time) an element in the collection of objects. This traditional interface has been superseded by iterators.

  

The difference between set and list
      • 1. The Set interface instance stores unordered, non-repeating data. The List interface instance stores 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. Finding elements is efficient, and insertion and deletion is inefficient because it causes other elements to change position < The implementation class has arraylist,linkedlist,vector> .

3.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, the class does not have a synchronization method, if multiple threads access a list at the same time, you must implement access synchronization yourself, the workaround is to create a list when a synchronous list is constructed. For example:

Listlist=collections.  Synchronizedlist(newlinkedlist(...));      

LinkedList lookup efficiency is low.

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. ArrayList increases the current length of 50% and inserts the deletion efficiency low.

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 by the Java.util package are 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

Hashtable is a subclass of the Dictionary (dictionary) class that is located in the Java.util package.

5 Properties
Properties inherit from Hashtable, which represents a persistent set of properties, and 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.

 

4. 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 set defines three static variables:empty_set,empty_list,empty_map . None of these variables can be changed.

5. 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.

1. Traverse ArrayList  

1  Public classtest{2   Public Static voidMain (string[] args) {3List<string> list=NewArraylist<string>();4List.add ("Hello");5List.add ("World");6List.add ("Hahahaha");7      //The first traversal method uses the Foreach traversal list8       for(String str:list) {//you can also rewrite for (int i=0;i<list.size (); i++) This form9 System.out.println (str);Ten      } One   A      //The second traversal, which transforms the linked list into array-related content to traverse -String[] Strarray=Newstring[list.size ()]; - List.toarray (strarray); the       for(inti=0;i<strarray.length;i++)//This can also be rewritten as a foreach (String str:strarray) Form -      { - System.out.println (Strarray[i]); -      } +       -     //the third kind of traversal uses iterators for related traversal +       AIterator<string> ite=list.iterator (); at       while(Ite.hasnext ())//determine the value after the next element -      { - System.out.println (Ite.next ()); -      } -  } -}

The third approach is to use an iterator method that does not worry about exceeding the length of the collection during the traversal.

2. Traverse Map
1  Public classtest{2       Public Static voidMain (string[] args) {3map<string, string> map =NewHashmap<string, string>();4Map.put ("1", "value1");5Map.put ("2", "value2");6Map.put ("3", "Value3");7       8       //The first type: Universal use, two-time value9System.out.println ("Traverse key and value through Map.keyset:");Ten        for(String key:map.keySet ()) { OneSystem.out.println ("key=" + key + "and value=" +Map.get (key)); A       } -        -       //The second Kind theSystem.out.println ("Using Iterator to traverse key and value through Map.entryset":); -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 ()); -       } +        A       //the third type: recommended, especially when the capacity is large atSystem.out.println ("Traverse key and value through Map.entryset"); -        for(Map.entry<string, string>Entry:map.entrySet ()) { -System.out.println ("key=" + entry.getkey () + "and value=" +Entry.getvalue ()); -       } -      -       //Fourth Type inSystem.out.println ("Traverse all value through Map.values (), but cannot traverse key"); -        for(String v:map.values ()) { toSystem.out.println ("value=" +v); +       } -      } the}

6. Summary

The Java Collection Framework provides programmers with pre-packaged data structures and algorithms to manipulate them.

A collection is an object that can hold references to other objects. The collection interface declares the actions that can be performed on each type of collection.

The classes and interfaces of the collection framework are in the Java.util package.

When any object is added to the collection class, it is automatically converted to the object type, so a forced type conversion is required when it is removed.

Java Basics--java Collection Framework

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.