Home  >  Article  >  Java  >  Introduction to Java framework usage

Introduction to Java framework usage

巴扎黑
巴扎黑Original
2017-07-18 15:45:503029browse

Collection interface

  • Collection is the most basic collection interface. A Collection represents a group of Objects, that is, the Elements.

  • All classes that implement the Collection interface must provide two standard constructors: a parameterless constructor for creating an empty Collection, and a Collection parameter constructor for Creates a new Collection that has the same elements as the passed Collection. The latter constructor allows the user to copy a Collection.

  • How to traverse each element in Collection? Regardless of the actual type of Collection, it supports an iterator() method, which returns an iterator. You can use this iterator to traverse and access each element in the Collection. Traversal through Iterator is seamless. The order is .

Typical usage is as follows:

1 Iterator it = collection.iterator(); // 获得一个迭代子2 while(it.hasNext()) {3      Object obj = it.next(); // 得到下一个元素4 }

List interface

  • List is an ordered Collection. Using this interface, you can precisely control the insertion position of each element. Users can access elements in the List using the index (the position of the element in the List, similar to an array subscript), which is similar to Java's array.

  • In addition to the iterator() method necessary for the Collection interface, List also provides a listIterator() method, which returns a ListIterator interface. Compared with the standard Iterator interface, ListIterator has more Some methods such as add() allow adding, deleting, setting elements, and traversing forward or backward.

  • Commonly used classes that implement the List interface are LinkedList, ArrayList, Vector and Stack.

LinkedList class

  • LinkedList implements the List interface, allowing null elements. In addition, LinkedList provides additional get, remove, and insert methods. These operations allow LinkedList to be used as a stack, queue, or deque.

  • Note that LinkedList has no synchronicity. If multiple threads access a LinkedList at the same time, you must implement access synchronization yourself. Another solution is to construct a synchronized List when creating the List: List list = Collections.synchronizedList(new LinkedList(...));

ArrayList Class

  • ArrayList implements a variable-sized array. It allows all elements, including null. ArrayList has no synchronicity.

  • size, isEmpty, get, set method running time is constant. However, the cost of the add method is an amortized constant, and adding n elements requires O(n) time. Other methods have linear running time.

  • Each ArrayList instance has a capacity (Capacity), which is the size of the array used to store elements. This capacity increases automatically as new elements are added, but the growth algorithm is not defined. When a large number of elements need to be inserted, the ensureCapacity method can be called to increase the capacity of the ArrayList before inserting to improve insertion efficiency.

Vector class

Vector is very similar to ArrayList, but Vector is synchronized. Although the Iterator created by Vector has the same interface as the Iterator created by ArrayList, because Vector is synchronized, when an Iterator is created and is being used, another thread changes the state of the Vector (for example, adding or removing some element), ConcurrentModificationException will be thrown when calling the Iterator method, so the exception must be caught.

Stack class

Stack inherits from Vector and implements a last-in-first-out stack. Stack provides 5 additional methods that allow Vector to be used as a stack. The basic push and pop methods, as well as the peek method, get the element on the top of the stack, the empty method tests whether the stack is empty, and the search method detects the position of an element in the stack. Stack is an empty stack after it is created.

Comparison of Vector, ArrayList and LinkedList

  1. 1. Vector is thread synchronized, so it is also thread-safe, while ArrayList and LinkedList are not Thread safe. If thread safety factors are not taken into consideration, it is generally more efficient to use ArrayList and LinkedList.

  2. 2.ArrayList and Vector implement data structures based on dynamic arrays, and LinkedList is a data structure based on linked lists.

  3. 3. If the number of elements in the collection is greater than the length of the current collection array, the Vector growth rate is 100% of the current array length, and the ArrayList growth rate is 50% of the current array length. %. If you use a relatively large amount of data in the collection, there are certain advantages to using vector; otherwise, there are advantages to using ArrayList.

  4. 3. If find data at a specified location, the time used by Vector and ArrayList is the same, and the time spent is O(1), while LinkedList needs to be traversed Searching takes O(i) time and is not as efficient as the first two.

  5. 4. And if moving and deleting the data at a specified location takes 0(n-i)n is the total length, you should consider using LinkedList at this time , because the time it takes to move data at a specified location is 0(1).

  6. 5. For inserting data at the specified location , LinedList has an advantage because ArrayList needs to move data.

Set interface

  • Set is a Collection that does not contain duplicate elements. That is, any two elements e1 and e2 have e1.equals(e2)=false, and Set has at most one null element.

  • Obviously, the Set constructor has a constraint that the passed-in Collection parameter cannot contain duplicate elements.

  • Please note: Mutable Objects must be handled with care. If a mutable element in a Set changes its state causing Object.equals(Object)=true, it will cause some problems.

Map interface

Please note that Map does not inherit the Collection interface, Map provides key to value mapping. A Map cannot contain the same key, and each key can only be mapped to one value.

The Map interface provides three types of set views. The content of the Map can be regarded as a set of key sets, a set of value sets, or a set of key-value mappings.

Hashtable class

  • Hashtable inherits the Map interface and implements a key-value mapping Hash table. Any non-null object can be used as key or value.

  • To add data, use put(key, value), and to remove data, use get(key). The time cost of these two basic operations is constant.

  • Hashtable adjusts performance through two parameters: initial capacity and load factor. Usually the default load factor 0.75 achieves a better balance between time and space. Increasing the load factor can save space but the corresponding search time will increase, which will affect operations like get and put.

  • Since the object used as a key will determine the position of the corresponding value by calculating its hash function, any object used as a key must implement the hashCode and equals methods. The hashCode and equals methods are inherited from the root class Object.

  • Hashtable is synchronous.

HashMap class

HashMap is similar to Hashtable, except that HashMap is asynchronous, and Allow null, that is, null value and null key. However, when treating HashMap as a Collection (the values() method can return a Collection), the time overhead of its iteration sub-operations is proportional to the capacity of the HashMap. Therefore, if the performance of iterative operations is very important, do not set the initial capacity of HashMap too high or the load factor too low.

TreeMap class

  • HashMap quickly searches its content through hashcode, disordered ; and all elements in TreeMap maintain a certain fixed order and are ordered.

  • HashMap is the best choice for inserting, deleting and positioning elements in Map. But if you want to iterate over keys in natural order or custom order, then TreeMap will be better. Using HashMap requires that the added key class clearly defines the implementation of hashCode() and equals().

  • TreeMap has no tuning options because the tree is always in a balanced state.

WeakHashMap class

WeakHashMap is an improved HashMap, which implements "weak reference" for key. If If a key is no longer referenced externally, the key can be recycled by GC.

##Summary

  • If operations involving stacks, queues, etc. are involved, you should consider using List ; For fast insertion and deletion of elements, LinkedList should be used; if fast random access to elements is required, ArrayList should be used.

  • If the program is in a single-threaded environment, or access is only performed in one thread, consider asynchronous classes, which are more efficient; if multiple threads may operate a class at the same time, Synchronized classes should be used.

  • Pay special attention to the operation of the hash table. The object used as the key must correctly override the equals and hashCode methods.

  • When using Map, it is best to use HashMap or HashTable to search, update, delete, and add; when traversing Map in natural order or custom key order, it is best to use TreeMap;

  • Try to return the interface rather than the actual type, such as returning List instead of ArrayList, so that if you need to replace ArrayList with LinkedList in the future, the client code does not need to change. This is programming for abstraction.

The above is the detailed content of Introduction to Java framework usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn