Project Note 1: Container usage and Problems

Source: Internet
Author: User
Tags iterable java util


Recently, the project encountered a permission topic tree generation problem. However, a small function is to save a list of non-Repeated Root elements, which may not be too well designed by the database.

Well, in the implementation process, I always need to parse the operation permissions. Very inconvenient. But it took some time to implement it, because I really don't want to change the hibernate ing any more. So

That's all. I originally wanted to use the List container to save the root column, but reported that an object in the List cannot be changed during the loop process. I want to determine if

The root element is inserted into the List, but this problem makes me very worried. On the Internet, I can use Iterator to remove elements. But cannot be added. So simply change the container and use HashSet,

Because Set does not allow repeated elements to be stored, it meets my requirements. You only need to rewrite the hashCode () and equals () Methods to define the conditions of the same object.

Because my table is a primary key auto-incrementing, we can use the primary key to determine whether it is the same. This function is implemented.

In the search, I found that a post about containers is very good, so I can turn to it for your convenience.

Bytes -------------------------------------------------------------------------------------

In the JAVA util package, there are two sets of parent Interface Collection and Map. Their parent-child relationship:
Java. util
+ Collection: extends: java. lang. Iterable
+ List Interface
-ArrayList class
-Shortlist class
-The Vector class implements synchronization.

+ Queue Interface
+ Not commonly used. This is not a table.

+ Set Interface
+ SortedSet Interface
-TreeSet class

+ Map interface
-HashMap class (except for not synchronizing and allowing the use of null keys/values, it is roughly the same as Hashtable .)
-The Hashtable class is synchronous and the null key value cannot be used.
+ SortedMap Interface
-TreeMap class

The following is a simple description of many interfaces and classes: first, let's not go over arrays)
I. Array, Arrays

Array is the most efficient method for Java's "Storage and random access to a series of objects.

High efficiency, but the capacity is fixed and cannot be changed dynamically.
Another disadvantage of array is that it cannot determine the actual number of elements in the array. length only tells us the array capacity.

2. There is an Arrays class in Java that is used to operate Arrays.
Arrays has a set of static functions,
Equals (): checks whether two arrays are equal. Array has the same number of elements, and all corresponding elements are equal to each other.
Fill (): Enter the value in array.
Sort (): used to sort arrays.
BinarySearch (): Search for elements in the sorted array.
System. arraycopy (): copying an array.

Ii. Collection and Map

If you do not know how many objects are needed when writing a program and need to automatically expand the capacity when the space is insufficient, you need to use the container class library. array is not applicable.

1. Differences between Collection and Map

The number of elements stored in each container is different.
Collection type, each location has only one element.
Map type, holding key-value pair, like a small database.

2. the Java2 container class library is used to "save objects". It is divided into two categories, each of which has its own subclass relationship.

-- List: stores elements in a specific order. Therefore, the order obtained may be different from the order placed.
-- ArrayList/Vector list/Vector
-- Set: duplicate elements cannot be contained.
-- HashSet/TreeSet
-- HashMap
-- HashTable
-- TreeMap

Map ---- A key-Value Pair object composed of a pair, that is, its elements are paired objects. The most typical application is data dictionary, and there are other extensive applications. In addition, Map can return a Set composed of all its keys and all its values, or a Set composed of its key-value pairs. It can also expand multi-dimensional Map like an array, you only need to make each "value" of the key-value pair in the Map a Map.

1. iterator under Collection

An iterator is a design pattern. It is an object that can traverse and select objects in a sequence. Developers do not need to understand the underlying structure of the sequence. An iterator is usually called a "lightweight" object because it is easy to create.

The Iterator function in Java is relatively simple and can only be moved one way:

(1) The method iterator () requires the container to return an Iterator. When the next () method of Iterator is called for the first time, it returns the first element of the sequence. Note: The iterator () method is a java. lang. Iterable interface inherited by Collection.

(2) Use next () to obtain the next element in the sequence.

(3) Use hasNext () to check whether there are any elements in the sequence.

(4) use remove () to delete the elements returned by the iterator.

Iterator is the simplest implementation of the Java Iterator. The ListIterator designed for List has more functions. It can traverse the List in two directions, or insert and delete elements from the List.

2. Functional methods of List

List (interface): Order is the most important feature of List. It ensures that the order of elements is maintained. List adds many methods to the Collection so that you can insert and remove elements to the List (only recommended for using the sort List ). A List can generate ListIterator, which can be used to traverse the List in two directions, or to insert and delete elements from the List.

ArrayList: List implemented by arrays. It allows fast and Random Access to elements, but it is slow to insert and remove elements into the List. ListIterator should only be used to traverse the ArrayList from the back to the back, rather than to insert and delete elements, because this is much more overhead than the aggregate list.

List: List implemented by the List. The sequential access is optimized, with little overhead for inserting and deleting data into the List. Random Access is relatively slow (can be replaced by ArrayList ). It has methods such as addFirst (), addLast (), getFirst (), getLast (), removeFirst (), removeLast (), these methods (not defined in any interface or base class) allow the consumer list to be used as a stack, queue, and bidirectional queue.

3. Functions and methods of Set

Set (interface): Each element stored in the Set must be unique, which is different from the List, because the Set does not store duplicate elements. The equals () method must be defined for the Object 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 HashSet can quickly locate an element. The object stored in the HashSet must define hashCode ().

TreeSet: Set that maintains 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.

HashSet uses the hash function to sort elements, which is specially designed for fast query. TreeSet uses the data structure of the red/black tree to sort elements. HashSet uses the hash function to speed up the query, at the same time, the linked list is used to maintain the order of elements, so that it seems that the elements are saved in the order of insertion. Note that when generating your own class, Set needs to maintain the storage sequence of the elements. Therefore, you must implement the Comparable interface and define the compareTo () method.

3. Other features

* List, Set, and Map objects are regarded as Object types.
* Collection, List, Set, and Map are all interfaces and cannot be instantiated.
The ArrayList, Vector, HashTable, and HashMap inherited from them are concrete classes, which can be instantiated.
* The vector container knows exactly the type of the object it holds. Vector does not perform boundary check.

Iii. Collections

Collections is a help class for the Collection class. Provides a series of static methods for searching, sorting, and thread-based operations on various sets.
It is equivalent to Arrays, a class that performs similar operations on Arrays.
For example, Collections. max (Collection coll); obtains the largest element in coll.
Collections. sort (List list); sorts the elements in the list.

4. How to choose?

1. Differences between the container class and Array
* The container class can only hold the object reference (pointer to the object), instead of copying the object information to a certain position in the series.
* Once an object is placed in a container, the type information of the object is lost.

* Among various Lists, it is best to use ArrayList as the default choice. Use the sort list () When insertion or deletion is frequent ();
Vector is always slower than ArrayList, so avoid using it whenever possible.
* In various Sets, HashSet is generally better than HashTree (insert and search ). TreeSet is used only when a sorted sequence is generated.
The only reason for the existence of HashTree is that it can maintain the sorting status of its elements.
* In various Maps
HashMap is used for quick search.
* When the number of elements is fixed, Array is used because the Array efficiency is the highest.

Conclusion: ArrayList, HashSet, HashMap, and Array are commonly used. In addition, we will also find a rule in which TreeXXX is sorted.


1. Collection does not have the get () method to obtain an element. You can only use iterator () to traverse elements.
2. Set and Collection have the same interface.
3. List. You can use the get () method to retrieve an element at a time. Use numbers to select one of a bunch of objects, get (0 ).... (Add/get)
4. ArrayList is generally used. Use the queue list to construct the stack and queue.

5. Map uses put (k, v)/get (k) and containsKey ()/containsValue () to check whether a key/value exists.
HashMap uses the hashCode of the object to quickly find the key.
* Hashing
The hash code transforms the object information to form a unique int value, which is stored in an array.
We all know that the array search speed is the fastest in all storage structures. Therefore, the search can be accelerated.

When a collision occurs, let the array point to multiple values. That is, an orders table is generated at each position of the array.

6. Elements in Map can be extracted separately from the key sequence and value sequence.
Use keySet () to extract the key sequence and generate a Set for all the keys in the map.
Use values () to extract the value sequence and generate a Collection for all values in the map.

Why does one generate a Set and one generate a Collection? That's because the key is always unique and the value can be repeated.


This article from the CSDN blog, reproduced please indicate the source:

Bytes -----------------------------------------------------------------------------------------------------

Today with SSH integrated fckeditor-java-2.4.1 + fckeditor2.6.3 also reported a weird error, there is no reasonable explanation on the Internet. I will send a screenshot to you.



No error is reported when it is used separately, that is, an error is reported when it is integrated with SSH. Thank you for your help. It's not too early. I went to bed first.



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