S2:java Collection Frame

Source: Internet
Author: User
Tags repetition

A Java collection is a container. Object-oriented language is the embodiment of things in the form of objects, so in order to facilitate the operation of multiple objects, the object is stored, the collection is the most common way to store objects. Collections are used only to store objects, the collection length is mutable, and collections can store different types of objects. If the base data type is stored in the collection, an automatic boxing and unpacking is available during the access process.

Because of the different data structures in the container, there are many kinds of containers. The general function is continuously extracted upward, forming a set system, called the set framework.

The top layer of the collection frame is called the collection interface. All collection classes are located under the Java.util package, and the lookup API can be structured as follows. When using a system, the principle: see top-level content. establishes the underlying object.

The difference between a collection and an array:

1: Array is fixed-length, set variable-length.

2: Arrays can store basic data types, or they can store reference data types, and collections can store only reference data types.

3: The elements stored in an array must be of the same data type, and the objects stored by the collection can be of different data types.

2. The list interface implements a list interface for common classes with ArrayList and LinkedList.  They can all accommodate all types of objects, including null, allow repetition, and guarantee the order in which elements are stored. The ArrayList Collection class ArrayList The array, implements the variable length arrays, and arrays with the same storage, allocates contiguous space in memory, and its advantage is that it is more efficient to traverse the elements and then access the elements. The various common methods defined in the list interface (which are also common methods of ArrayList) are shown in the table below.

return type

Method

Description

Boolean

Add (Object o)

Add an element at the end of the list, starting at index 0

void

Add (int index,object o)

At the specified index position element Note: The index position must be between 0 and the number of elements in the list

Int

Size ()

Returns the number of elements in a list

Object

Get (int index)

Returns the element at the specified index note: The removed element is of type object and requires a forced type conversion before use

Boolean

Contains (Object o

Determines whether the specified element exists in the list

Boolean

Remove (Object o)

Remove an element from the list

Object

Remove (int index)

Removes the specified position element from the list, starting at the starting index position from 0

Compare: The similarities and differences between Vector and ArrayList. Prior to the advent of the ArrayList class, there was a collection class Vector in the JDK that also allocated contiguous storage space and implemented a variable length array. The two implementations have the same principle, the same functions, and in many cases can be interoperable. The main differences between the two are as follows
    • Vector is thread-safe, ArrayList heavy speed and light security, is thread non-security, so when running into a multi-line program environment, the programmer needs to manage the synchronization of the thread.

    • When the length needs to grow, the Vector increases by default by a factor of one, while the ArrayList only increases by 50%, saving memory space.
In the development process, it is best to use the new version of ArrayList. The LinkedList Collection class LinkedList uses the list storage method, the advantage is that the insertion, deletion element is more efficient, it provides additional addfirst (), AddLast (), Removefirst () and removelast (), etc. You can insert or delete operations at the LinkedList header or tail. These methods enable the LinkedList to be used as a stack or a pair of columns (queue). Let's summarize the various common methods of LinkedList. LinkedList In addition to the various methods listed earlier, there are some special methods, see the table below.

return type

Method

Description

void

AddFirst (Object o)

Add an element to the header of the list

void

AddLast (Object o)

Add an element at the end of the list

Object

GetFirst ()

Returns the first element in a list

Object

GetLast ()

Returns the last element in a list

Object

Removefirst ()

Delete and return the first element in a list

Object

Removelast ()

Delete and return the last element in the list

3. A map interface is provided in the Map Interface Java Collection framework, specifically to handle the storage of key-value mapping data.  A map can store multiple elements, each consisting of two objects, a key object and a value object that can be mapped according to the corresponding values. The map interface stores a pair of key-value objects that provide a mapping of the key (key) to value. The key in the MAP does not require ordering and does not allow duplication. Value also does not require ordering, but allows repetition. The most common Map implementation class is HASHMAP, which is stored in a hash table, with the advantage that querying a specified element is highly efficient. The various common methods defined in the Map interface (which are also common methods of HashMap) are shown in the table below.

return type

Method

Description

Object

Put (Object key,object value)

Store in a key-value pair Note: The key must be unique and the value can be duplicated. If you attempt to add a duplicate key, the last key-value pair is added to replace the original key-value pair.

Object

Get (Object key)

Returns NULL if the specified key does not exist, based on the value associated with the health return.

Object

Remove (Object key)

Deletes a key-value pair that is mapped by the specified key

Int

Size ()

Returns the number of elements

Set

KeySet ()

Returns a collection of keys

Collection

VALUES ()

A collection of return values

Boolean

ContainsKey (Object key)

Returns true if there is a "key-value pair" that is mapped by the specified key

Comparison:
Similarities and differences of Hashtable and HASHMAP.
Before the HashMap class appeared, there was a collection class Hashtable in the JDK that also implemented the key-value mappings in the same way that it was stored in a hash table. The two implementations have the same principle, the functions are the same, and in many cases they can be interoperable.
The main differences between the two are as follows.
    • Hashtable inherits from the Dictionary class, and HashMap implements the Map interface.
    • Hashtable is thread-safe, HashMap heavy-speed, lightweight, and thread-insecure, so when running into a multithreaded environment, the programmer needs to manage the synchronization of the thread itself.
    • Hashtable does not allow null values (both key and value are not allowed), and HashMap allows null values (both key and value allow).
In the development process, it is best to use the new version of HashMap. Traversal mode:
Import java.util.collection;import Java.util.hashmap;import Java.util.iterator;import Java.util.Map;import Java.util.map.entry;import Java.util.set;public class Map {public static void main (string[] args) {//Traversal mode 1:map<       String,string>c=new hashmap<string,string> ();       C.put ("CN", "China");       C.put ("RU", "Russia"); C.put ("FR", "France"); Set<string> Set=c.keyset (); for (String Key:set) {System.out.println (key); System.out.println (C.get (key));} Traverse mode 2:system.out.println ("====================================="); Collection<string> c1=c.values (); for (String values:c1) {System.out.println (values);} Traverse mode 3:system.out.println ("======================================="); Set<entry<string, string>> C2=c.entryset (); for (entry<string, string> entry:c2) { System.out.println (Entry.getkey ()); System.out.println (Entry.getvalue ());} Traverse mode 4:system.out.println ("============================="); Set<string>keyset=c.keyset ();iterator<string> IteratoR=keyset.iterator (); while (Iterator.hasnext ()) {String key=iterator.next (); SYSTEM.OUT.PRINTLN (key); System.out.println (C.get (key));} Traverse mode 5:system.out.println ("==============================="); iterator<entry<string, String>> c3= C.entryset (). iterator (); while (C3.hasnext ()) {entry<string, string> en=c3.next (); System.out.println (En.getkey ()); System.out.println (En.getvalue ());}}}

  

4. Iterator I Terator all the collection interfaces and classes do not provide a corresponding traversal method, but instead pass the traversal over to the iterator Iterator complete. Iterator is a collection, which implements the traversal of the collection. It hides the internal details of the various collection implementation classes and provides a unified programming interface for traversing the collection.
The iterate () method of the Collection interface returns a Iterator, which can then be easily traversed by the two methods of the Iterator interface.
    • Boolean Hasnext (): Determines whether there is another accessible element.
    • Object next (), which returns the next element to be accessed.
5 generic Collection The argument to the Add (object obj) method mentioned earlier in the Collection is the Obect type, regardless of which object is placed in the Collection and its sub-interfaces or implementation class, and is considered to be just the type of object, at the Get (int index) Method must be forced to cast the elements in the collection, not only cumbersome but also prone to classcastexception exceptions. When using put (object Key,object value) and get (object key) to access an object in Map, the same problem exists when fetching an element using the Iterator Next () method.
This problem is effectively solved by introducing generics (Generic) in JDK1.5. All interfaces and classes in the collection framework have been rewritten in JDK1.5, adding support for generics.
When you create a collection object by using a generic collection, you specify the type of the elements in the collection, you do not need to type-cast when you remove the elements from the collection, and a compilation error occurs if you put a non-specified type object into the collection. Comparison:
The main differences between arrays and collections include the following.
    • Arrays can store basic data types and objects, and only objects can be stored in the collection (the base data types may be stored as wrapper classes).
    • The length of the array is fixed and the set length can be changed dynamically.
    • The array element type must be specified when the array is defined, and all of the elements in the collection are Object by default.
    • You cannot directly get the number of elements that the array actually stores, length is used to get the lengths of the array, but the number of elements actually stored by the collection can be obtained directly through size ().
    • Collections are implemented in a variety of ways and in different applications, unlike arrays that only use allocated contiguous spaces.
    • The collection is in the form of interfaces and classes, has the characteristics of encapsulation, inheritance and polymorphism, and can realize various complex operations through simple method and property invocation, greatly improving the development efficiency of software.
The JDK has a Arrays class that is designed to manipulate arrays, which provides a series of static methods for searching, sorting, comparing, and populating an array. There is a Collection class in the JDK that is dedicated to manipulating the collection, which provides a series of static methods for searching, assigning, sorting, and threading security for various collections. Summing up the ① collection makes up for the defect of the array, it is more flexible and practical than the array, can greatly improve the development efficiency of the software, and the different sets can be applied to different occasions.
The ② collection framework is a uniform standard architecture defined for representing and manipulating collections. The collection framework contains three chunks of content: external interfaces, interface implementations, and algorithms for set operations.
③ usually says that there are three main types of interfaces in the Java collection framework: List,set and Map, the difference is as follows.
    • The Collection interface stores a set of non-unique, unordered objects.
    • The set interface inherits the Collection interface, which stores a set of unique, unordered objects.
    • The List interface inherits the Collection interface, storing a set of non-unique, ordered objects.
    • The map interface stores a key-value object that consists of pairs, providing a mapping of key to value. Key does not require ordering and does not allow duplication. Value also does not require ordering, but allows repetition.

④arraylist and arrays Use the same storage, which has the advantage of traversing elements and randomly accessing elements at a higher efficiency. The advantage of LinkedList is that it is efficient to insert and delete elements when they are stored in a linked list.
⑤hashmap is the most common Map implementation class, which is stored in a hash table, with the advantage that querying a specified element is highly efficient.
⑥iterator, which is built for collections, implements the traversal of a collection, which hides the internal details of various sets of implementation classes and provides a unified programming interface for iterating through the set.
⑦ uses generics to specify the type of elements in the collection when the collection object is created, eliminating the need for a type cast when extracting elements from the collection, avoiding the classcastexception exception.

S2:java Collection Frame

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.