Java attack (3) Container class

Source: Internet
Author: User
Tags map class

Zookeeper

A container is a series of class instances provided by Java API, used to store objects in programs. A container can manage the lifecycle of an object and the dependency between the object and the object. Java container classes include List, ArrayList, Vector and map, HashTable, HashMap, and Hashset.

The class diagram structure of container API is as follows:



1. Collection Interface


Collection is the most basic Collection interface. All classes that implement the Collection interface must provide two standard constructor: A non-parameter constructor is used to create an empty Collection, A constructor with the Collection parameter is used to create a new Collection, which has the same elements as the imported Collection. The next constructor allows you to copy a Collection. The two interfaces derived from the Collection interface are List and Set.


Ps: For the methods defined in the Collection interface, refer to them.


Ii. List Interface


List is an ordered Collection, which can be used to precisely control the insert position of each element. You can use an index (the position of an element in the List, similar to an array subscript) to access the elements in the List, which is similar to an array in Java. Unlike set, the list usually allows repeated elements. To be more precise, the list usually allows e1.equals (e2) elements to pair e1 and e2, and if the List itself permits null elements, they usually allow multiple null elements.

Common classes that implement the List interface include the List, ArrayList, Vector, and Stack. Lateral List: List implemented by two-way linked List at the underlying layer. Features: Low query efficiency, high addition and deletion efficiency, and Low thread security. ArrayList: List implemented by arrays at the underlying layer. Features: High query efficiency, low addition and deletion efficiency, and insecure threads. Vector: List implemented by arrays at the underlying layer. Features: thread security. Stack: the Stack inherits from the Vector to implement a post-import, first-out Stack. Stack provides five additional methods to make the Vector used as a Stack. Ps: For the methods defined in the List interface, refer to them.

Usage principle: Use Vector for thread safety. The thread is not secure. ArrayList is used for searching. You can add or delete multiple elements in the sequence list.


Iii. Set Interface


Set is a Collection that does not contain repeated elements, that is, the two elements e1 and e2 both have e1.equals (e2) = false, and Set has a maximum of null elements. The equals () method must be defined for the element added to the Set to ensure the uniqueness of the object. Set has the same interface as Collection. The Set interface does not guarantee the order of maintenance elements.


HashSet: A Set designed for quick search. The object stored in the HashSet must define hashCode (). TreeSet: The Set that stores the order. The bottom layer is the tree structure. It can be used to extract ordered sequences from the Set. LinkedHashSet: query speed with a HashSet, and internal use of the linked list to maintain the order of elements (insert order ). When you use the iterator to traverse the Set, the result is displayed in the order of element insertion.



Iv. Map Interface


Note that Map does not inherit the Collection interface. Map provides the key ing between key and value. A Map cannot contain the same key, and each key can only Map one value. The Map interface provides three sets of views. The Map content can be treated as a set of keys, a set of values, or a set of key-value ing.

Implementation classes of the Map interface include HashMap and TreeMap. HashMap: The thread is unsafe and efficient. The key or value is allowed to be null. HashTable: thread security and low efficiency. The key or value is not allowed to be null.

Ps: Key-value pairs stored in the Map class are identified by keys, so the key-value pairs cannot be repeated.


Example:

Import java. util. *; class MapTest {public static void main (String [] args) {Map m1 = new HashMap (); Map m2 = new HashMap (); m1.put ("one ", new Integer (1); m1.put ("two", new Integer (2); m1.put ("three", new Integer (3); m2.put ("", new Integer (1); m2.put ("B", new Integer (2); System. out. println (m1.size (); // m1 length. The result is 3 System. out. println (m1.containsKey ("one"); // If m1 contains a file named one, the result is true System. out. println (m2.containsValue (new Integer (2); // if m2 contains 2 values, the result is true if (m1.containsKey ("two ")) {// m1 whether it contains int I = (Integer) m1.get ("two") named two ")). intValue (); System. out. println (I); // obtain the value named two and print it. The result is 2} Map m3 = new HashMap (m1); m3.putAll (m2 ); // put m1 and m2 into m3 and print them. The result is the key and value System contained in m1 and m2. out. println (m3 );}}

Result:

5. iterator Interface


All the containers that implement the Collection interface have an iterator method to return an iterator interface. The Iterator object is called an iterator to facilitate the traversal of elements in the container.


The Iterator interface defines the following methods:


Boolean hasNext (); // determines whether any element is not traversed.


Object next (); // returns the element at the current position of the cursor and moves the cursor to the next position.


Void remove (); // Delete the elements on the left of the cursor. This operation can only be performed once after the next operation is completed.


6. Others (understanding)


Comparable interface:


All classes that can be sorted implement the java. lang. Comparable interface. The Comparable interface has only one method:


Public int compareTo (Object obj );


Returns 0 to indicate this = obj;


Returns a positive number indicating this> obj;


Returns a negative number indicating this <obj;


The class that implements the Comparable interface determines the sorting method of the class objects by implementing the comparaTo method.


Equals and hashcode methods:


Whether Collection objects are equal objects must be compared when calling methods such as remove and contains. This involves the equals and hashCode methods of object types. For custom types, you need to override the equals and hashCode methods to implement custom object equality rules. Java stipulates that two objects with the same content should have equal hashcode.

When do we need to rewrite the equal and hashcode methods? What is the purpose?

The purpose is to make your class work in concert with java's collection framework. If we can confirm that the class we define does not have a relationship with the java Collection class, there is no need to overwrite the hashCode when overwriting the equals () method.

In the following cases, we may need to rewrite the equal/hashcode method:

To put our custom object into HashSet for processing; to process our custom object as the key of HashMap; to put the custom object in the Collection container, remove may be called, contains and other methods.

Relationship and principle between Equal and hashcode: 1. Hashcode is not a memory address, but a memory address is converted. The system can also determine the memory address. 2. The hashcode method is mainly used in the set framework to quickly compare whether two objects are equal. Because there are many objects in the set framework, it is inefficient to use equals for each object.

Each object has a hashcode, which stipulates: 1. The hashcode of the object with the same content must be equal. 2. The hashcode of the object with different content may be equal or not equal.

Therefore, if the hashcode of the two objects is not equal, the content of the two objects is definitely not equal. In this way, you do not have to compare the attribute values one by one, thus improving the object comparison speed.

Vector:

The Vector is synchronized. Some methods in this class ensure that the objects in the Vector are thread-safe. ArrayList is asynchronous, so the objects in ArrayList are not thread-safe. Because the synchronization requirements will affect the execution efficiency, it is a good choice to use ArrayList if you do not need a thread-safe set, this avoids unnecessary performance overhead due to synchronization.

In terms of the internal implementation mechanism, both ArrayList and Vector use arrays to control objects in the set. When adding elements to these two types, if the number of elements exceeds the current length of the internal array, both of them need to extend the length of the internal array, by default, Vector automatically doubles the length of the original array. ArrayList is 50% of the original length, so the space occupied by the final set is always larger than actually needed. Therefore, if you want to save a large amount of data in the Set, using Vector has some advantages, because you can avoid unnecessary resource overhead by setting the initialization size of the set.

In ArrayList and Vector, it takes the same time to search for data from a specified position (through an index) or add or remove an element at the end of the set, if you only search for elements at a specific position or add or remove elements only at the end of the set, you can use Vector or ArrayList. For other operations, it is best to select another set operation class. For example, the LinkList collection class takes the same time to add or remove any element from the set, but it does not take much time to index an element. it is also easy to use ArrayList, because you can simply use indexes instead of creating iterator objects. LinkList also creates an object for each inserted element, so it also brings additional overhead.



Summary

If operations such as stacks and queues are involved, you should consider using the List. For elements that need to be inserted and deleted quickly, you should use the random List. If you need to quickly access elements randomly, you should use the ArrayList.


Pay special attention to the operations on the hash table. The equals and hashCode methods should be correctly rewritten as the key object.


Try to return the interface rather than the actual type. For example, if the List is returned rather than the ArrayList, the client code does not need to be changed if you need to replace the ArrayList with the explain List later. This is for abstract programming.


If the program is in a single-threaded environment or the access is only performed in one thread, the efficiency of non-synchronous classes is high. If multiple threads may operate on one class at the same time, synchronous classes should be used.


Finally, we recommend that you use a simple Array instead of Vector or ArrayList. This is especially true for programs with high execution efficiency requirements. Array is used to avoid synchronization, additional method calls, and unnecessary Space reallocation.




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.