Dark Horse programmer: A Collection framework in Apis

Source: Internet
Author: User
Tags set set

---------- Android training, Java training, and hope to communicate with you!
----------

After learning so many frameworks, I will summarize the usage and differences between frameworks today:

First, let's take a general diagram of the Framework in Java, as shown below:

 

Collection

1. List: The elements are ordered and can be repeated. Because the collection system has indexes.

2. Set: elements are unordered and cannot be duplicated.

List

1. arraylist: the underlying data structure uses an array structure. Feature: Fast query speed. However, adding, deleting, and deleting are slow. The thread is not synchronized.

2. linked list: the underlying linked list data structure. Features: Fast addition, deletion, and slow query. The thread is not synchronized.

3. Vector: the bottom layer is the array data structure. Thread synchronization. Replaced by arraylist. Low efficiency.

List: special method. Any method that can operate the badge is unique to the system.

Add:

Add (index, element );

Addall (index, collection );

Delete:

Remove (INDEX );

Change:

Set (index, element );

Query:

Get (INDEX ):

Sublist (from, );

Listiterator ();

Int indexof (OBJ): gets the position of the specified element.

Listiterator ();

Listiterator is a list-specific interface and listiterator is a subinterface of iterator.

Listiterator can traverse and execute the curd operation

In iterator, there are only hasnext (), next (), and remove () methods.

Except list: special method:

Addfirst ();

Addlast ();

Add Element

Getfirst ();

Getlast ();

Obtain elements, but do not delete them. If no element exists in the collection, nosuchelementexception exception occurs.

Removefirst ();

Removelast ();

Get the element, but the element is deleted. If no element exists in the collection, nosuchelementexception exception occurs.

An alternative method is available in jdk1.6.

Offerfirst ();

Offerlast ();

Add Element

Peekfirst ();

Peeklast ();

Obtain elements, but do not delete them. If no element exists in the Set, null is returned.

Pollfirst ();

Polllast ();

Get the element, but the element is deleted. If no element exists in the Set, null is returned.

These methods of linklist can simulate the storage process of heap and stack.

Set

1. hashset: the underlying data structure is a hash table. Is thread unsafe. Do not synchronize.

2. treeset: You can sort the elements in the Set set.

Use set to save elements. The elements are unique.

1. How does a hashset save unique elements?

Is done through two methods of elements, hashcode and equals.

If the hashcode value of the element is the same, the system checks whether equals is true.

Equals is not called if the hashcode value of an element is different.

If both hashcode and equals are the same, the two elements are the same, and the added elements are not stored in the hashset.

Therefore, we often need to overload the hashcode and equals methods in the process of using hashset, and call them when determining whether they are the same element.

2. How does treeset ensure that elements are unique?

The underlying data structure of treeset is a binary tree. The basis for ensuring element uniqueness: compareto method return 0.

(1) The first method of treeset sorting: Make the elements have a comparison. The comparable interface must be implemented to override the compareto method. It also becomes the natural sequence of elements, or the default sequence.

(2) The second sorting method of treeset: When the element itself does not have the comparison, or the comparison is not required. In this case, the set itself needs to be compared. That is, a comparator is defined on its constructor, which is passed as a parameter to the constructor treeset (comparator <?
Super E> comparator)

The implementation process of the comparator is to define a class, implement the comparator interface, and overwrite the compare method.

Therefore, when using treeset, the comparator interface is often implemented without a comparator to overwrite the compare method.

Map

Map set: This set stores key-value pairs. One to one. The key must be unique.

1. hashtable: the data structure of the hash table is at the underlying layer, and the null key value cannot be saved. This set is synchronized by threads. Jdk1.0.

2. hashmap: the bottom layer is the data structure of the hash table. The null value and the null key are allowed. This set is not synchronized. Replace hashtable with jdk1.2.

3. treemap: The underlying layer is the binary tree data structure. The thread is not synchronized. It can be used to sort keys in the map set.

Some special methods in map:

1. Add put (K key, V value)

Only one value can be added at a time: When the map has the same key, the added value will overwrite the original value.

2. Delete

Clare (): clear map

Remove (Object key): deletes Objects Based on the specified key and returns a deleted value. If the key does not exist, null is returned.

3. Judgment

Containsvalue (object value)

Containskey (Object key)

Isempty ()

4. Get

Get (Object key): determines whether the object exists based on the key value. If the object does not exist, null is returned.

Size (): map size

Values (): returns all values.

Entryset ()

Keyset ()

Two unique retrieval methods in map: entryset () and keyset ()

1, set <k> keyset:

Store all the keys in the map to the Set set. Because set has an iterator.

All the keys that can be retrieved iteratively are obtained according to the get method. Obtains the value corresponding to each key.

Principle of Map Collection removal: converts a map set into a set. In the iterator.

2, set <map. Entry <K, V> entryset:

Saves the ing relationships in the map set to the Set set,

The data type of this link is map. Entry.

The entry is actually a static internal interface in map.

Map. Entry is actually an interface, which is an internal interface in the map interface.

interface Map{public static interface Entry{public abstract Object getKey();public abstract Object getValue();}}class HashMap implements Map{class Hahs implements Map.Entry{public  Object getKey(){}public  Object getValue(){}}}

Extended Application of MAP: one-to-many relationship

Example: one school has multiple classes and one class has many students:

Key code (czbk is the zhuzhi podcast School, which has two classes: reyu and Jiuye ):

HashMap<String,List<Student>> czbk = new HashMap<String,List<Student>>();List<Student> reyu = new ArrayList<Student>();List<Student> jiuye = new ArrayList<Student>();czbk.put("yureban",reyu);czbk.put("jiuyeban",jiuye);reyu.add(new Student("01","zhagnsa"));reyu.add(new Student("04","wangwu"));jiuye.add(new Student("01","zhouqi"));
Collections

Tool class of the Collection framework.

Collections: tool class of the Collection framework. All static methods are defined in it.

What is the difference between collections and collection?

Collection is a top-level interface in the Collection framework, which defines the common methods of a single column set.


It has two common sub-interfaces,

List: all elements are indexed. Ordered. Elements can be repeated.

Set: elements cannot be repeated. Unordered.

Collections is a tool class in the Collection framework. The methods in this class are static.


In the provided methods, you can sort the list set and perform binary search.

Generally, common collections are thread-insecure. Because we need to improve efficiency.

If multiple threads operate on these sets, you can use the synchronization method in this tool class to convert the sets with unsafe threads into secure

Arrarys

Arrays: A Tool class used to operate arrays. Static Methods
1) aslist (): the array can be changed to list

What are the advantages of converting an array into a list set?

You can use the idea and method of the set to operate the elements in the array.

Note: changing an array to a set does not allow the addition or deletion of a set. Because the length of the array is fixed.

If you add or delete a file. The unsupportedoperationexception will be thrown.

Special notes:

1. If all elements in the array are objects. When it becomes a set, the elements in the array are directly converted into elements in the set.

2. If the elements in the array are of the basic data type, the array (an element) will exist as the elements in the set.

Incorrect syntax:

Int [] num = {, 2, 44 };

List <integer> List = arrays/aslist (Num );

Correct syntax:

Integer [] num = {, 2, 44 };

List <integer> List = arrays/aslist (Num );

2) Changing the array of Sets

The toarray method in the collection interface.

1. Convert string [] S = (string []) collection. toarray ()

2. String [] S = collection. toarray (New String [collection. Size ()])

1. How long does an array of the specified type need to be defined?

If the length of an array of the specified type is smaller than the size of the set, a new array is created in this method. The length is the size of the set.

If the length of an array of the specified type is greater than the size of the set, no new array is created. Instead, use the passed array. Therefore, it is best to create an array that is just right.

2. Why should we change the set to an array?

To restrict operations on elements. No need to add or delete

 

---------- Android training, Java training, and hope to communicate with you!
----------

See http://edu.csdn.net/heima/ for details

 

 

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.