Collection classes in Java -- Review

Source: Internet
Author: User

Chapter 2 Collection classes in Java
10.1 collection class and data container
Java uses collection classes to accommodate different types of data. This kind of data is based on the unknown, that is, Java uses a limited collection class to accommodate infinite types of data objects.
Category
The data structure of a linear table represented by Arrays
Using Collection as the base class-encapsulates basic operations such as insert and delete of linear tables
The data structure of the key-Value Pair represented by Map
Map-based class-encapsulates the structure of "key-value" Pairs
10.2 linear table type set
A set of linear tables can be used to describe and enable data objects stored in a linear table (sequence. Including arrays, vectors, lists, stacks, and sets.
An example of sequence access-array class
Arrays are the most common Linear tables. The action of defining and using arrays is implemented by referencing (that is, returning a reference to a newly created array through the new Keyword). You can also use array references to access array elements.
In Example 10.1, write a program to show how to initialize an array and access an array object.
Note: arrays and various Collection types described later are all "containers" that can save data and objects ".
Limitations of the μ array object
Ü arrays cannot better meet the demand for dynamic growth.
Ü once the elements in the array are determined, it takes a lot of resources to insert or delete the elements in the array.
Linked List Interface
In the data structure of a linear table, there is a structure for storing and managing data in a "chain" way, called a "linked list ".
Comparison between the storage mode and the array in the μ Chain
Micro java. util. list interface: encapsulates the "store and manage data in the form of a linked List" function. If you use a class that implements the List interface, such as the Vector and sorted List classes, you can use the linked list to store data.
μ void add (int index, E element) inserts an object after index
μ boolean add (E o) inserts the object o to the end of the linked list.
Μe remove (int index) deletes the element with the specified index number in the linked list.
Μboolean remove (Object o)
Delete the first specified Element in the linked list.
μ E get (int index) to get the element with the specified index number in the linked list.
Μint size () returns the number of elements in the linked list.
Μint indexOf (Object obj)
If the obj element is found in the linked list, the index value of this element is returned. If not,-1 is returned.
Μlist <E> subList (intfromIndex, int toIndex)
Obtain the sublinked list from fromIndex to toIndex.
Micro void clear ()
Removes all elements stored in the linked list. This method is generally called after the linked list is used.
Slave Stack class
Stack is also a Data Structure of the linear table type.
μ features: a container of the "Last In First Out" type, that is, the Last object that is pushed into the stack, the first pop will pop up.
μ Constructor
Micro Stack (): used to create objects that support "post-in-first-out" Access
For example, Stack st = newStack ();
Stack <String> st = newStack ();
Other methods
Μe peek () returns the top element of the stack, but no top element of the stack is displayed.
μ E pop () pops up the top element of the stack and returns the objects in it.
μ E push (E item) pushes the item object to the top of the stack, and returns the item object.
μ boolean empty () determines whether the stack is empty. If the stack is empty, true is returned. Otherwise, false is returned.
Note: Because Stack inherits the Vector class, the following statements are syntactically correct. However, it breaks the "first-in-first-out" feature of the stack. Therefore, it is not recommended.
St. addElement ("bad usage1 ");
St. addElement ("bad usage2 ");
St. addElement ("bad usage3 ");
For (int I = 0; I <st. size (); I ++ ){
System. out. println (st. elementAt (I ));
}
10.3 The Set interface with duplicate elements is not allowed.
The Set interface not only encapsulates the method for managing objects using linear tables, but also encapsulates the function of "No repeated elements can be inserted, therefore, you can use Set to avoid repeated elements with high efficiency.
Primary methods in the sorted Set Interface
μ boolean add (E o) adds elements to the Set object. If the element to be inserted does not exist in the Set object, true is returned after the add action is executed. The element is not inserted again and false is returned.
μ boolean remove (Object o) deletes the specified Element in the Set Object. If this method successfully deletes the specified Element in the Set object, true is returned; otherwise, false is returned.
μ boolean isEmpty () determines whether the Set object is null. If the Set object contains elements, this method returns true; otherwise, false.
Μint size () returns the number of elements in the Set object.
Worker implements the HashSet class of the Set interface.
The "hash-based" Method for Detecting duplicate elements: the element values in the HashSet correspond to the index locations of the elements stored in the Set (hash function ), before inserting an element in a HashSet, you can calculate the insert position of the element in the HashSet based on the value and corresponding relationship) if the value of the element to be inserted already exists, the element cannot be inserted.
μ Constructor
Ü HashSet ()
Ü HashSet (<E> c)
Other methods
Ü boolean contains (Object o) determine whether a specified element exists
Example 10.6 comprehensive application of the HashSet class.
Set <String> set = newHashSet <String> ();
Set. add ("One"); set. add ("One ");
System. out. println (set. size (); // number of output elements: 1
Set. add ("Two"); System. out. println (set. size (); // number of elements: 2
System. out. println (set. contains ("One"); // true, containing the element "One"
Summary
The first collection has a common feature: the objects they store are all mona1 (linear), but the storage method is different from the data structure used, the Collection class encapsulates basic operations such as insert and delete of linear tables.
Both the List interface and the Set interface are sub-interfaces of Collection.
Implement the List interface: stores data based on linear linked lists, such as Vector

Implement the Set interface: they do not allow repeated elements, such as HashSet.
10.4 set of "key-value" Pairs
In Java, we create a "key-value" pair type object represented by HashTable, "key"-index information, and "value"-information corresponding to the index value.
In Java, we create a "key-value" pair type object represented by HashTable, "key"-index information, and "value"-information corresponding to the index value.
If you want to query the specified data from it, you have to traverse the array in sequence, so the efficiency will be very low.
(2) Another Way of Thinking: saving 10 to the array is not inserted in the first free space!
μ there is an index conflict problem: for hash functions, different "values" will get the same "key", that is, different objects may be stored in the same index location.
Solution
Ü adopt technical methods, such as designing a hash function to minimize the occurrence of a conflict, or specifying a response policy when a conflict occurs;
Ü based on the amount of data to be stored, appropriately increase the capacity of Hash tables-use the cost of increasing space to obtain the low probability of conflict occurrence
A typical example of a key-Value Pair-Hashtable class
In Java's "key-value" pair type Collection class, we have encapsulated the Implementation Details of optimizing the data search efficiency and handling data conflicts in the Hash table using Hash functions. Hashtable is a model of key-Value Pair collection classes.
μ Constructor
Ü Hashtable ()
Ü Hashtable (int initialCapacity)
Ü Hashtable (int initialCapacity, float loadFactor)
Ü Hashtable (<K, V> t)
Specify the type of keys and values in the Hash table using generics, for example:
 
Other methods
Ü V put (K key, V value): insert the "key-value" pair to the Hashtable object
Ü V get (Object key): retrieves the corresponding "value" from the Hashtable Object based on the "key" of the key"
For example, ht. put (newInteger (1), new String ("Tom "));
String str = ht. get (new Integer (1 ));
Ü boolean containsKey (Object key)
Determines whether the "key" exists in the Hashtable object.
Ü boolean containsValue (Objectvalue)
Determine whether the value exists in Hashtable.
For example, booleanflag = ht. containsKey (new Integer (2 ));
Flag = ht. containsValue ("Rose ");
Ü public boolean contains (Object value) is the same as the containsValue () method.
Ü public void clear ()
Clear this Hashtable so that it does not contain any keys.
For example, use the 10.7Hashtable class.
Note: using the ht. put (newInteger (3), new Integer (27); statement, reset the "value" 27 with the "key" as 3. If two "values" are set for the same "key", the last action takes effect.
Summary:
The common feature of the second type of set is that the data they store is binary, and they are called "key-value" pairs, they can quickly obtain the corresponding value based on a key keyword. Here, they are called keywords because they must be unique, in this way, the value obtained through the key is fixed each time, that is, the value that was last set.
10.5 enumerators and Data Operations
The Enumerator is a tool used to access collection elements. It not only provides a number of methods that can be used to access the set, but also shows the idea of solving the problem of "uncertain object type" when accessing objects.
The "uncertainty" problem of the ingress Access Collection class
Java has many different types of Java Collection classes (such as Vector or List). programmers want to access the data in the same type.
Handler Interface
Java. util. Iterator (enumerator Interface) encapsulates the "no difference access set object" method.
Relevant Methods
Ü each collection class (such as Vector or Hashtable) has an iterator () method. Each collection object can use this method to control the traversal of this class to the Iterator interface.
Ü in the Iterator interface, the boolean hasNext () method is provided to determine whether the next element in the Set object can be obtained through the enumerator.
Ü in the Iterator interface, the E next () method is provided to obtain the next element in the Set object. It returns a generic object.
For example, use the 10.10 enumerator.
Vector <Integer> v = new Vector <Integer> ();
For (int I = 0; I <5; I ++ ){
V. addElement (new Integer (I ));
}
Iterator it = v. iterator ();
While (it. hasNext ()){
System. out. println (it. next (). toString ());
}
The idea of "separating" the encryptor
The design concept of "traversing different types of collection objects" is "separated;
The service action traversal is separated from the object to be traversed (such as a set). On this basis, the common code for Traversing objects in different sets is abstracted, encapsulate these functional code into the interface of the enumerator, and you can use the same set of code to traverse different types of sets;
It is precisely because the enumerator separates the Business Action (enumeration) from the data (SET) to be operated by the Business Action, so it can remain unchanged.

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.