Frame Structure of collection

Source: Internet
Author: User

Often see the use of the recordset in the program, commonly used are collection, HashMap, HashSet, ArrayList, because it is not clear the relationship between them, so in use often confused, so that do not know where to start. Here is a small example, hoping to help you straighten out the idea.
First look at their relationship:
Collection
--list:-----------------------store elements in a particular order. So the order taken out may be different from the order in which it is put.
---ArrayList
---linkedlist
---Vector
--set:-----------------------does not contain duplicate elements
---HashSet
---TreeSet
Map
---HashMap
---HashTable
---TreeMap
Add:
List,set,map the data that is deposited is treated as an object type.
Collection, List, Set, and map are interfaces and cannot be instantiated. The ArrayList, vectors, and Hashtable,hashmap, which inherit from them, are the figurative class, which can be instantiated.
Vectors do not perform boundary checks.
Let's take a look at the specific examples:
Collection
Defines a collection object that points to a newly created instance of its subclass:
Collection C = new ArrayList () This is the so-called "parent class reference to a Subclass object", which is used to represent the newly created ArrayList, as long as C. Next, assign a value to it.
C.add ("06s030014");
C.add ("hit");
C.add ("CS");
C.add ("WH");
And then how to remove it, the subclass that implements the collection interface has a iterator () method that can be called to return an object of type iterator, which can be used to remove the desired value. The code is as follows:
Iterator It=c.iterator ()
string s = (string) it.next ();
This is just to take out one of the data, in order to get everything out, you can use the loop
For (Iterator it=c.iterator (); It.hasnext ();) {
string s = (string) it.next ();
}

Subclasses that implement the collection interface can access data in a way similar to the above.
HashMap
HashMap differs from collection, whose object does not have a iterator () method, but it has a values () method that returns a collection object after this method is called, and the iterator () method is called by the returned object to implement fetching data.
There is also a get () method to get the data, but only a single record can be fetched. Look at the following example
HashMap hm1 = new HashMap ();
Book BK1 = new book ("001", "Java Learning", "Higher Education");
Book BK2 = new book ("002", "Tomcat Configuration", "Tsinghua University Press");
Book BK3 = new book ("003", "JSP", "mechanical Industry");
Hm1.put ("Book1", BK1);
Hm1.put ("Book2", BK2);
Hm1.put ("Book3", BK3);
Where book is the books class, there are three properties: Bookid,bookname,bookpub. See the attached code for details.
Call the put () method to save three of the book's objects in HashMap, corresponding to the name Book1,book2,book3
Two ways to fetch data
First Kind
Iterator ITT = Hm1.values (). Iterator ();
Book Bkex = (book) itt.next ();
The first record is taken out, which is noted in the post-existing first fetch [as to why I cannot say clearly]
The second Kind
Book Tempbook = (book) hm1.get ("Book3");
This allows the corresponding record to be extracted directly from the name.

These are some of the experiences I have come up with and I hope to be of some help to you. We also welcome further discussion!
The attachment is the complete code for the example.
Here is a detailed description of the linear table, linked list, Hashtable, data from the Internet. After watching it will help deepen their understanding! Linear table, linked list, hash table is a common data structure, in Java development, the JDK has provided us with a series of corresponding classes to implement the basic data structure. These classes are all in
Java.util in the package. This article attempts to explain to the reader the functions of each class and how to use them correctly through a simple description.

Collection
├list
│├linkedlist
│├arraylist
│└vector
│└stack
└set
Map
├hashtable
├hashmap
└weakhashmap

Collection interface
Collection is the most basic set interface, and a collection represents a set of object, the collection element (Elements). Some collection allow the same meta
Vegetarian and others are not. Some can sort and others can't. The Java SDK does not provide classes that inherit directly from collection, and the Java SDK provides classes that inherit from collection.
Sub-interfaces, such as list and set.
All classes that implement the collection interface must provide two standard constructors: the parameterless constructor is used to create an empty collection, and there is a collection parameter
The constructor of the number is used to create a new collection, and the new collection has the same elements as the incoming collection. The latter constructor allows the user to copy a
Collection.
How do I traverse every element in the collection? Regardless of the actual type of collection, it supports a iterator () method that returns an iteration that enables
Each element in the collection can be accessed one at a time using the iteration child. Typical usage is as follows:
Iterator it = Collection.iterator (); Get an iteration child
while (It.hasnext ()) {
Object obj = It.next (); Get the next element
}
The two interfaces that are derived from the collection interface are list and set.

List interface
The list is an ordered collection, using this interface to precisely control where each element is inserted. The user is able to use the index (the position of the element in the list, similar to the array
To access the elements in the list, similar to the Java array.
Unlike the set mentioned below, the list allows the same elements.
In addition to the iterator () method, which has the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, and a standard
Compared to the iterator interface, Listiterator has a number of add () methods that allow adding, deleting, setting elements, and traversing forward or backward.
The common classes that implement the list interface are Linkedlist,arraylist,vector and stacks.

LinkedList class
The LinkedList implements a list interface that allows null elements. Additionally LinkedList provides an additional Get,remove,insert method at the first or the tail of the LinkedList. These exercises
The LinkedList can be used as a stack, queue, or two-way queue (deque).
Note LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a list with the same
List of steps:
List List = Collections.synchronizedlist (new LinkedList (...));

ArrayList class
ArrayList implements a variable-size array. It allows all elements, including null. ArrayList is not synchronized.
Size,isempty,get,set method run time is constant. But the Add method cost is the allocated constant, and adding n elements requires an O (n) time. Other methods run at a linear time
Each ArrayList instance has a capacity (capacity), which is the size of the array used to store the elements. This capacity increases automatically as new elements are added, but grows
The algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to improve insertion efficiency.
Like LinkedList, ArrayList is also unsynchronized (unsynchronized).

Vector class
Vectors are very similar to ArrayList, but vectors are synchronous. The iterator created by the vector, although the same interface as the iterator created by ArrayList,
is synchronized for the vector, when a iterator is created and is being used, another thread changes the state of the vector (for example, by adding or removing some elements), the call
The iterator method throws Concurrentmodificationexception, so the exception must be caught.

Stack class
Stack inherits from Vector and implements a last-in-first-out stack. The stack provides 5 additional ways to make the vector available as a stack. The basic push and pop methods, but also
The Peek method gets the top element 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 has just been created as an empty stack.

Set interface
Set is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element.
Obviously, the constructor of a set has a constraint that the passed-in collection parameter cannot contain duplicate elements.
Note: Variable objects (Mutable object) must be handled with care. If a mutable element in a set changes its state, the Object.Equals (Object) =true will
Cause some problems.

Map interface
Note that map does not inherit the collection interface, and map provides a key-to-value mapping. A map cannot contain the same key, and each key can only map one value. Map connection
The port provides a view of 3 collections, and the contents of the map can be treated as a set of key sets, a set of value collections, or a set of key-value mappings.

Hashtable class
Hashtable inherits the map interface to implement a key-value mapped hash table. Any object that is not empty (non-null) can be either a key or a value.
Add data using put (key, value), take out the data using get (key), the time overhead for these two basic operations is constant.
The Hashtable adjusts performance through the initial capacity and load factor two parameters. Normally the default load factor 0.75 is a good way to achieve a balanced time and space
。 Increasing the load factor can save space but the corresponding lookup time will increase, which will affect operations like get and put.
A simple example of using Hashtable is to put the three-to-one in the Hashtable, with their key being "single", "Two", "three":
Hashtable numbers = new Hashtable ();
Numbers.put ("One", New Integer (1));
Numbers.put ("n", New Integer (2));
Numbers.put ("Three", New Integer (3));
To take out a number, say 2, with the corresponding key:
Integer n = (integer) numbers.get ("a");
System.out.println ("both =" + N);
Because an object that is a key will determine the position of its corresponding value by calculating its hash function, any object that is a key must implement the Hashcode and Equals methods.
The hashcode and Equals methods inherit from the root class object, and if you use a custom class as key, be very careful, as the hash function defines, if two objects are the same,
Obj1.equals (OBJ2) =true, their hashcode must be the same, but if two objects are different, their hashcode may not be different if the hashcode of two different objects
In the same way, this phenomenon is called a conflict, which causes the time overhead of manipulating the hash table to be increased, so the hashcode () method can be defined so as to speed up the operation of the hash table.
If the same object has different hashcode, the operation of the hash table will have unexpected results (expect the Get method to return null), to avoid this problem, just keep in mind
One: To replicate the Equals method and the Hashcode method at the same time, instead of just writing one of the two.
The Hashtable is synchronous.

HashMap class
HashMap and Hashtable are similar, except that HashMap is non-synchronous and allows NULL, which is null value and null key. , but HashMap is considered
When collection (The values () method returns collection), its iterative sub-operation time overhead is proportional to the capacity of the HashMap. Therefore, if the performance of an iterative operation is quite important
, do not set the initialization capacity of the hashmap too high, or load factor too low.

Weakhashmap class
Weakhashmap is an improved hashmap, which implements a "weak reference" to key, which can be recycled by GC if a key is no longer referenced externally.

Summarize
If it involves operations such as stacks, queues, and so on, you should consider using the list, for quick insertions, for deleting elements, should use LinkedList, if you need to quickly randomly access elements,
You should use ArrayList.
If the program is in a single-threaded environment, or if access is done only in one thread, it is more efficient to consider a class that is not synchronized, and if multiple threads might manipulate a class at the same time, you should
Use a synchronized class.
Pay special attention to the operation of the hash table, and the object as key should correctly replicate the Equals and Hashcode methods.
Try to return the interface rather than the actual type, such as returning a list instead of ArrayList, so that if you need to change ArrayList to LinkedList later, the client code does not have to be changed.
This is for abstract programming



Answer to the interview question
The difference between Collection and collections.
Collections is a Java.util class that contains a variety of static methods related to collection operations.
Collection is an interface under Java.util, which is the parent interface of various collection structures.
Does the List, Set, and map inherit from the collection interface? List,set is map is not
The difference between ArrayList and vectors.
I. Synchronization: vector is thread-safe, that is, synchronous, and ArrayList is a thread program is not secure, not synchronous
Two. Data growth: When growth is needed, vectors grow by default to the original, while ArrayList is half the original
The difference between HashMap and Hashtable
I. Historical reasons: Hashtable is based on the old dictionary class, HashMap is an implementation of the map interface introduced by Java 1.2
Two. Synchronization: Hashtable is thread-safe, that is, synchronous, and HashMap is a thread program is not secure, not synchronous
Three. Value: Only HashMap can let you use NULL as the key or value of an entry for a table

Frame Structure of collection

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.