Set operation class in java (to be continued), java to be continued

Source: Internet
Author: User
Tags addall

Set operation class in java (to be continued), java to be continued
Statement:

Intern's superficial understanding. If you find any mistakes, I hope you can give me more advice.

Nonsense

In fact, every time I write a java background operation, I encounter a statement: List <XXXXX> list = new ArrayList <XXXXX> ();

But I only know that the list class is a class of object instances that can be stored with variable length. I even think this List object can be understood as an array, but it is different from the array we normally understand in java. For example, the length of the array can automatically increase as needed. For example, instantiating a List class is different from declaring an array!

Today's internship is a bit boring. I opened eclipse and read the code written by my colleagues. I accidentally saw this sentence again, so I decided to take a look at this kind of operation-the container class (Collection class) in java)

Body

Steal a picture first. I won't tell you that I stole it from Baidu encyclopedia.


We can see that there are two main types of Set Operations in java: Collection set and Map ing.

Collection

Collection is a top-level interface, which is an abstraction of a java Set. On this basis, two subinterfaces are derived: List and Set

List
The List interface has ordered features. The stored objects can be null and repeat is allowed. This is very different from the set interface. The Set interface cannot be repeated. The List interface is similar to an array, access to List objects can be accessed through a subscript similar to an array, but through the get (int index) method. At the same time, its actual length is similar to an array, and it can be accessed through size () returns the actual length of an iterator () method. In addition to the Iterator () method required for the Collection interface, List also provides a listIterator () method to return a ListIterator interface. Compared with the standard iterator interface, listIterator has some add () and other methods, allowing you to add, delete, set elements, and traverse the elements forward or backward. List common methods: add(E e): Add the specified element to the end of the list.
add(int index,E element): Insert a specified element to a specified position in the list.
addAll(Collection<? extendsE> c): Add all elements in the specified collection to the end of the list. The order is the order in which the iterator of the specified collection returns these elements.
addAll(int index,Collection<? extendsE> c): Inserts all elements in the specified collection into the specified position in the list and compares it with the array. The list query efficiency is high, but the insertion and deletion efficiency is low, because insertion and deletion may cause changes in the positions of other elements clear(): Remove all elements from the list
contains(Object o): If the list contains the specified element, return True
containsAll(Collection<?> c): If the list contains all elements of the specified collectionTrue
get(int index): Return the elements at the specified position in the list.
indexOf(Object o): Returns the index of the specified element that appears for the first time in this list. If this list does not contain this element,-1 is returned.
iterator(): Returns the iterator that iterates over the elements in the list in the appropriate order.
lastIndexOf(Object o): Returns the index of the last specified Element in the list. If the list does not contain this element,-1 is returned.
listIterator(): Returns the list iterator for this list element (in the appropriate order)
listIterator(int index): Return the list iterator of the elements in the list (in the proper order), starting from the specified position in the list
remove(int index): Removes the elements at the specified position in the list.
remove(Object o): Removes the specified element that appears for the first time from the list.
removeAll(Collection<?> c): Removes all the elements contained in the specified collection from the list.
retainAll(Collection<?> c): Only the elements contained in the specified collection are retained in the list.
set(int index,E element): Replace the specified position element in the list with the specified element.
size(): Returns the number of elements in the list.
subList(int fromIndex,int toIndex)Return toFromIndex(Including) andToIndex(Not included) partial views
toArray(): Returns an array containing all elements in the list in the appropriate order.

For details about the method, refer to the list interface in the API, including ArrayList, sorted list, Vector, and Stack.
The ArrayList can be identified by its name. It is often similar to an array.

ArrayList implements an array of variable sizes. It allows all elements, including null. The ArrayList is not synchronized. Only the Vector implements synchronization (thread-safe). Each ArrayList instance has a Capacity, that is, the size of the array used to store elements. The default value is 10. This capacity can automatically increase with the addition of new elements, but the growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensureCapacity method (set the minimum length) before insertion to increase the ArrayList capacity to improve insertion efficiency. Like the synchronized list, ArrayList is also non-synchronous (unsynchronized)

Case:
Package test; import java. util. arrayList; import java. util. iterator; import java. util. list; public class Test {public static int flg = 0; public int self = 0; public Test () {++ flg; self = flg; System. out. println ("initialized:" + flg + "instances");} public static void main (String [] args) {// TODO Auto-generated method stub/** adding the paradigm Test indicates that the Test type is stored here. After obtaining the specific value, you can access the methods and attributes of the object, such as list. get (I ). flg * if no paradigm is added, the self attribute or other attributes cannot be accessed. Method */List <Test> list = new ArrayList <Test> (); for (int I = 0; I <5; I ++) {list. add (new Test (); System. out. println (list. get (I ). self);} list. add (new Test (); System. out. println (list. get (list. size ()-1 ). self); list. addAll (list); System. out. println (list. size (); list. add (0, null); System. out. println (list. get (0); // use the Iterator to traverse. Note that you must add a generic Iterator <Test> myiterator = list to the Iterator. listIterator (); Test test; while (myiter Ator. hasNext () {test = myiterator. next (); if (test! = Null) System. out. println (test. self); elseSystem. out. println (test );}}}
Shortlist

The listlist interface allows null elements. In addition, the values list provides additional get, remove, and insert methods at the beginning or end of the values list. These operations enable the queue list to be used as a stack, queue, or two-way queue (deque). This class implements the Deque interface, the add and poll methods are provided to implement FIFO queue operations, and other stack and bidirectional queue operations are performed together.

Note that the synchronized list method is not available. If multiple threads access a List at the same time, they must implement access synchronization by themselves. One solution is to construct a synchronized List when creating a List:

List list = Collections. synchronizedList (new Collections List (...));

Case:

Basic operations

<Span style = "font-size: 14px;"> package test; import java. util. iterator; import java. util. using list; import java. util. list; public class Test {public static int flg = 0; public int self = 0; public Test () {++ flg; self = flg; System. out. println ("initialized:" + flg + "instances");} public static void main (String [] args) {// TODO Auto-generated method stub/** adding the paradigm Test indicates that the Test type is stored here. After obtaining the specific value, you can access the methods and attributes of the object, such as list. get (I ). flg * if no paradigm is added, you cannot access this self attribute or other methods */List <Test> list = new external List <Test> (); int I = 0; test test = new Test (); list. add (0, test); while (I <5) {list. add (new Test (); I ++;} System. out. println ("indexOf:" + list. indexOf (test); System. out. println ("lastIndexOf:" + list. lastIndexOf (test); System. out. println ("contants:" + list. contains (test); System. out. println ("contants:" + list. contains (new Test (); // pay attention to the use of the iterator and specify the correct generic type for the iterator, iterator <Test> iterator = list. listIterator (); while (iterator. hasNext () {System. out. println (iterator. next (). self) ;}}</span>

As for everyone, the consumer list can be used as a queue or a stack. On the surface, consumer List implements Deque and Other interfaces, which can be used in this way. However, in practice, I don't know how the producer list instance is. I don't have the poll method provided in the api, so I didn't do this case here, but the simulation is very simple.

VectorVector is similar to ArrayList, but it is indeed synchronized. That is to say, it is thread-safe. In other words, if a Vector creates an iterator, when this iterator is in use, another thread changes the status of this Vector, and the usage of this Vector is similar to that of ArrayList. Refer to the above and the API.
Stack: something that I learned in the data structure. I used to be familiar with it before, but now I am new to it. I probably know that there is a feature: LIFO first-in-first-out, in java, Stack is Vector-based. In addition to the basic push () and pop () methods, java Stack also provides a peek () method to get the top element value of the Stack, the empty method determines whether it is null. The search method looks for the position of an element in the stack. Since the List interface is implemented, there will be some simple examples of the list Operation Method:
Package test; import java. util. stack; public class Test {public static int flg = 0; public int self = 0; public Test () {++ flg; self = flg; System. out. println ("initialized:" + flg + "instances");} public static void main (String [] args) {// TODO Auto-generated method stubStack stack = new Stack (); for (int I = 0; I <5; I ++) stack. push (I); System. out. println (stack. peek (); System. out. println (stack. size (); int len = stack. size (); for (int I = 0; I <len; I ++) System. out. println (stack. pop (); System. out. println (stack. size ());}}

Set

Set is a Collection interface that cannot be repeated. set retrieval efficiency is relatively low. Compared with list, insertion and deletion are more efficient and will not cause changes in the positions of other elements, set is unordered. The biggest difference between Set and List is that Set cannot be repeated.

We need to remember that this guy cannot be repeated.

The reason that Set cannot be repeated is that it is implemented based on Map, while the key in Map cannot be repeated. In Set, only the key in Map is used.


Set common methods. For details, refer to the Java API

Add (E): If no specified element exists in the set, add this element.

AddAll (Collection <? ExtendsE> c): If no elements in the collection are specified in the set, add them to the set.

Clear (): removes all elements in this set.

Contains (Object o): returns true if set contains the specified element.

ContainsAll (Collection <?> C): If this set contains all elements of the specified collection, true is returned.

Equals (Object o): Compares the equality between the specified Object and the set.

IsEmpty (): returns true if set does not contain elements.

Iterator (): The iterator that returns the elements in this set for iteration.

Remove (Object o): If a specified element exists in the set, remove it.

RemoveAll (Collection <?> C): remove the elements in the set that are contained in the specified collection.

RetainAll (Collection <?> C): only the elements in the set contained in the specified collection are retained.

Size (): returns the number of elements in the set.

ToArray (): returns an array containing all elements in the set.

It is quite painful. The get method is not used in the set to obtain element objects, and data can only be accessed through the iterator.

Common Set implementation classes include TreeSet, HashSet, and javashashset.

TreeSetTreeSet is actually ordered. The default value is natural sequence. You can use the built-in or custom sorting method. When creating a TreeSet, you can pass a custom sorting rule object. Since it is ordered and implemented based on TreeMap, the element object in the TreeSet must implement the Comparable interface, however, if it is a String object, the String itself has implemented the Comparable interface. Obviously, no get method is found during the test and the iterator method is displayed, this means that you can only access detailed data through the iterator. A simple case: You need to implement the Comparable interface (String is not required, String is already implemented, but you can write another one, use your own definition)
Package test; import java. util. iterator; import java. util. set; import java. util. treeSet; public class Test implements Comparable <Test> {public static int flg = 0; public int self = 0; public Test () {++ flg; self = flg; System. out. println ("initialized:" + flg + "instance") ;}@ Overridepublic int compareTo (Test o) {// TODO Auto-generated method stubif (this. self <o. self) return-1; else if (this. self> o. self) return 1; elsereturn 0;} public static void main (String [] args) {// TODO Auto-generated method stubSet set = new TreeSet (); for (int I = 0; I <5; I ++) set. add (new Test (); System. out. println (set. size (); Iterator <Test> it = set. iterator (); while (it. hasNext () {System. out. println (it. next (). self );}}}
HashSet

Like TreeSet, data can only be accessed through the iterator. HashSet is implemented based on HashMap, but unordered. Common methods are similar to the Set interface. Remember one thing, the access must pass through the iterator. The iteration sequence cannot be consistent with the insertion sequence, which is exactly the opposite of the LinkedHashSet.

Case: To be supplemented

LinkedHashSet

LinkedHashSet is a linked list structure. It is consistent with the above. It is traversed through the iterator, but the traversal order is consistent with the insertion order.

Case: To be supplemented

Map

(In fact, I used to learn about Map from the Hibernate class. The teacher said that when I learned java, the teacher ended the course when I talked about the basic loop structure. It was terrible)

Map is a top-level interface that mainly processes the key ing (key/value) type and is used to store key-value pairs

The Map interface provides three Collection views, allowing you to access a mapped content in the form of a key set, value set, or key-Value Pair ing relationship set, the iteration sequence is defined as the sequence of elements returned by the iterator in the collection view. Some Map implementations can ensure the sequence, such as TreeMap, but some cannot, such as HashMap.

Constructor:

There are two constructor Methods: one is no parameter, and the other is a parameter with a Map type.

Common method: put method: Add a key-value pair. Here we will introduce Map as an example.

Map interfaces are implemented mainly by TreeMap and HashMap.

TreeMap is implemented based on the NavigableMap balanced binary tree of the Red-Black tree. The ing is sorted by the natural sequence of its keys, or by the Comparator provided when the ing is created, depending on the construction method used.
Constructor: TreeMap (): uses the natural sequence of keys to construct a new, empty tree ing.
TreeMap (Comparator <? SuperK> comparator) to construct a new, empty tree ing. The ing is sorted Based on the given comparator.
TreeMap (Map <? ExtendsK ,? Extends V> m) to construct a new tree ing that has the same ing relationship with the given ing. The ing is sorted according to the natural order of its keys.
TreeMap (SortedMap <K ,? ExtendsV> m) to construct a new tree ing with the same ing relationship and the same sorting order as the specified ordered ing.

Common Methods: Map. Entry <K, V> ceilingEntry (K key)
Returns a key-value ing relationship entity that is associated with the smallest key greater than or equal to the given key. If such a key does not exist, null is returned.
Get (Object key): returns the value mapped to the specified key. If the key does not contain any ing relationship, null is returned.
KeySet (): returns the Set view of the key contained in the ing.
NavigableKeySet (): return the NavigableSet view of the keys contained in the ing.
Values (): returns the Collection view of the values contained in this ing.
Put (K key, V value): Associate the specified value with the specified key in the ing.
PutAll (Map <? ExtendsK ,? Extends V> map): Copies all mappings in the specified ing to this ing.
Remove (Object key): If this TreeMap contains a ing relationship for this key, delete it.

HashMap

Implementation of the Map interface based on the hash table. This implementation provides all optional ing operations and allows the use of null values and null keys. (The HashMap class is roughly the same as that of Hashtable except for non-synchronous and allowed null .) This class does not guarantee the order of mappings, especially it does not guarantee that the order remains unchanged.

This implementation assumes that the hash function distributes elements appropriately between buckets and provides stable performance for basic operations (get and put. The time required to iterate the collection view is proportional to the "capacity" (number of buckets) of the HashMap instance and its size (number of key-value ing relationships. Therefore, if iteration performance is important, do not set the initial capacity too high (or set the loading factor too low)

For more information, see the API. I am tired at night and don't want to write it.









Java has several collections.

3. I remember asking during the interview...

Set, list, and map ).

The difference is that HASHMAP only corresponds to KEY and value values .. Set can automatically identify the same element
The list object is stored in a linear way. There is no specific order, and there is only one beginning and one end. Of course, it is different from a set with no sequence at all.
In the data structure, the list is represented by arrays and vectors, linked lists, stacks, and queues.

In Java, how can a set be used?

List: stores ordered and repeatable elements.
Set: stores unordered elements that cannot be duplicated.
Map: an element in the key-value format. All the keys constitute a set, and all the values constitute a List set.

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.