Some understandings of the collection framework

Source: Internet
Author: User
Tags addall comparable

Collection frame: ★★★★★, a container for storing data.
Characteristics:
1: Objects encapsulate data, and objects need to be stored. Collection is used to store objects.
2: The number of objects determines the array can be used, but is not sure what to do? You can use collections. Because the collection is variable-length.

The difference between a collection and an array:
1: Array is fixed-length, set variable-length.
2: Arrays can store basic data types, or they can store reference data types, and collections can store only reference data types.
3: The elements stored in an array must be of the same data type, and the objects stored by the collection can be of different data types.

Data structure: Is the way in which a container is stored.

For collection containers, there are many kinds. Because each container's own characteristics are different, the principle is that each container's internal data structure is different.
The collection container is in the process of continuous upward extraction. There is a collection system.
When using a system, the principle: see top-level content. establishes the underlying object.

–< java.util >–collection Interface:
Collection:
|–list: Ordered (the order in which elements are stored in the collection is consistent with the order in which they are taken), and the elements are indexed. Elements can be duplicated.
|–set: Unordered (the deposit and fetch order may be inconsistent), cannot store duplicate elements. Element uniqueness must be guaranteed.

1, add:
Add (object): Adds an element
AddAll (Collection): Adds all the elements in a collection.
2, Delete:
Clear (): Removes all elements from the collection, emptying the collection.
Remove (obj): Deletes the specified object from the collection. Note: The length of the collection will change if the deletion succeeds.
RemoveAll (collection): deletes some elements. Some elements are consistent with incoming collection.
3, Judge:
Boolean contains (obj): whether the specified element is contained in the collection.
Boolean Containsall (Collection): Whether the collection contains the specified number of elements.
Boolean isEmpty (): whether there are elements in the collection.
4, Get:
int size (): There are several elements in the collection.
5, take the intersection:
Boolean Retainall (Collection): The same element in the current collection that is persisted and specified in the collection. Returns flase if the two collection elements are the same, or true if Retainall modifies the current collection.
6, gets all the elements in the collection:
Iterator Iterator (): iterator
7, turn the collection into an array:
ToArray ();

–< java.util >–iterator Interface:
Iterator: is an interface. Function: Used to take an element in a collection.
Boolean Hasnext () returns True if there are still elements that can iterate.

Next () returns the next element of the iteration.

void Remove () removes the last element returned by the iterator from the collection that the iterator points to (optional action).

Each collection has its own data structure and has a specific way of extracting its own internal elements. To facilitate the operation of all containers, remove the element. The method of removing the inside of the container is provided as a uniform rule, which is the iterator interface.
It is also said that as long as the elements in the collection collection can be removed through the interface, it is not necessary to take into consideration the specific removal details of each specific container based on its own data structure, thus reducing the coupling of the element to be taken and the specific set.

Iterator it = Coll.iterator ();//Gets the iterator object in the container, as to what this object is not important. This object certainly conforms to a rule iterator interface.

public  static  void  main  (string[] args) {Collection coll = new  ArrayList (); Coll.add ( "abc0" ); Coll.add ( "ABC1" ); Coll.add ( "ABC2" ); //--------------Way 1---------------------- Iterator it = Coll.iterator (); while  (It.hasnext ()) {System. out . println (It.next ()); } //---------------mode 2 with this type of---------------------- for  (Iterator it = Coll.iterator (); It.hasnext ();) {System. out . println (It.next ()); } }

–< java.util >–list Interface:
The list itself is a sub-interface of the collection interface and has all the collection methods. Now learning the common method peculiar to list system, the method of lookup finds that the unique method of list has index, which is the most characteristic of this set.

List: Ordered (the order in which elements are stored in the collection is consistent with the order in which they are taken), and the elements are indexed. Elements can be duplicated.
|–arraylist: The underlying data structure is an array, the thread is out of sync, the ArrayList replaces the vector, and the query element is fast.
|–linkedlist: The underlying data structure is linked list, the thread is not synchronized, adding or deleting elements is very fast.
|–vector: The underlying data structure is an array, thread synchronization, Vector regardless of query and additions and deletions are huge slow.

1, add:
Add (index,element): Inserts an element at the specified index bit.
AddAll (index,collection): Inserts a bunch of elements at the specified index bit.
2, Delete:
Remove (Index): Deletes the element at the specified index bit. Returns the element that was deleted.
3, Get:
Object Get (Index): Gets the specified element by index.
int indexOf (obj): Gets the index bit of the first occurrence of the specified element if the element does not exist return-1;
So, by 1, you can tell if an element exists.
int lastIndexOf (Object o): Reverse index Specifies the position of the element.
List sublist (start,end): Gets the child list.
4, modify:
Object Set (index,element): Modifies elements of the specified index bit.
5, get all the elements:
Listiterator Listiterator (): A list collection-specific iterator.

The list collection supports adding, deleting, changing, and checking elements.

The list collection is because the corner label has its own way of acquiring elements: traversal.

for(int x=0; x<list.size(); x++){    sop("get:"+list.get(x));}

When iterating through the list elements, if you want to manipulate elements during an iteration, such as satisfying a condition to add a new element. Will happen. Concurrentmodificationexception Concurrency modification exceptions.
The causes are:
A collection reference and an iterator reference operate an element at the same time, and after the collection is fetched to the corresponding iterator, the element that is referenced by the collection is added in the iteration, and the iterator does not know, so an exception occurs.

How to solve it?
Now that you are working with elements in an iteration, it is most appropriate to find an iterator. But there are only hasnext,next,remove methods in iterator. By looking at its sub-interface, Listiterator, the list iterator interface has the added, deleted, modified, Check the action.

Listiterator is an iterator that is unique to the list collection.
Listiterator it = list.listiterator;//Replaces iterator it = list.iterator;
Method Summary
void Add (e e) Inserts the specified element into the list (optional operation).

Boolean Hasnext () returns True if the list iterator has more than one element when it iterates through the list (in other words, true if Next returns an element instead of throwing an exception).
Boolean hasprevious () returns True if the list iterator has more than one element, if it is traversed in reverse.

Next () returns the next element in the list.

int Nextindex () returns the index of the element returned by subsequent calls to next.

Previous () returns the previous element in a list.

int Previousindex () returns the index of the element returned by subsequent calls to previous.

void Remove () removes the last element returned by next or previous from the list (optional action).

void Set (e e) replaces the last element returned by next or previous with the specified element (optional operation).

The principle of variable-length arrays:
When the element exceeds the length of the array, a new array is generated, the data from the original array is copied to the new array, and the new elements are added to the new array.
ArrayList: Is 50% extended according to the original array. Constructs an empty list with an initial capacity of 10.
Vector: Is extended by 100% of the original array.

Note: For the list collection, the underlying judgment element is the same, and its utility is done by the Equals method of the element itself. Therefore, the proposed elements are to replicate the Equals method, to establish the element object's own comparison of the same conditions.

LinkedList: A unique method.
AddFirst ();
AddLast ();
After the jdk1.6.
Offerfirst ();
Offerlast ();

GetFirst (): Gets the first element in a linked list. If the linked list is empty, throw nosuchelementexception;
GetLast ();
After the jdk1.6.
Peekfirst (); Gets the first element in a linked list. Returns null if the linked list is empty.
Peeklast ();

Removefirst (): Gets the first element in the list, but deletes the first element in the linked list. If the linked list is empty, throw nosuchelementexception
Removelast ();
After the jdk1.6.
Pollfirst (); Gets the first element in the list, but deletes the first element in the linked list. Returns null if the linked list is empty.
Polllast ();

–< java.util >–set Interface:
The methods in the set interface are consistent with the methods in the collection. The set interface is removed in only one way, an iterator.
|–hashset: The underlying data structure is a hash table, and threads are not synchronized. disorderly, efficient;
The HashSet Collection guarantees element uniqueness: Through the Hashcode method of the element, and by the Equals method.
When the hashcode value of the element is the same, it continues to determine whether the equals of the element is true.
If true, then the same element is considered not saved. If False, then store.
If the hashcode value is different, then equals is not judged, thus increasing the speed of object comparisons.
|–linkedhashset: Ordered, HashSet sub-class.
|–treeset: The ordering of the specified order of elements in the set collection. Different steps. TreeSet the underlying data structure is a binary tree.

the principle of a hash table:
1, the key words in the object element (unique data in the object), the hash algorithm operation, and a specific algorithm value, this value is called the hash value.
2, the hash value is the position of this element.
3, if there is a conflict in the hash value, again determine whether the same object for this keyword is the same. If the objects are the same, they are not stored because the elements are duplicated. If the object is different, it is stored and deferred on the original object's hash value base +1.
4, the structure that stores the hash value, which we call a hash table.
5, since the hash table is stored according to the hash value, it is best to ensure that the object's keywords are unique in order to improve efficiency.
This can be as few as possible to determine whether the corresponding object of the same keyword, improve the operation efficiency of the hash table.

For ArrayList sets, it is the Equals method to determine whether an element exists or to delete an element's underlying basis.
For HashSet collections, determine whether an element exists, or delete an element, based on the Hashcode method and the Equals method.

TreeSet:
Used to sort the specified order of elements in the set collection, and the ordering needs to be based on the comparison of the elements themselves.
If the element is not comparable, a ClassCastException exception occurs at run time.
So we need elements to implement comparable interface, forcing elements to have a comparative, CompareTo method of replication.
Determines the position of the element in the TreeSet data structure, based on the return value of the CompareTo method.
The TreeSet method guarantees the uniqueness of the element by means of a reference to whether the result of the comparison method is 0, and if return 0 is treated as a two object repetition, does not exist.

Note: When comparing, if the judgment element is not unique, for example, the same name, same age, is considered the same person.
In the judgement, the main conditions and secondary conditions need to be divided, when the main conditions are the same, then judge the secondary conditions, sorted by the secondary conditions.

TreeSet collections are sorted in two ways, comparable and comparator differ:
1: Let the element itself have the comparison, need element object implements comparable interface, overwrite CompareTo method.
2: To make the collection itself comparable, you need to define a comparer that implements the comparator interface, override the Compare method, and pass the class object as the actual argument to the TreeSet collection's constructor.
The second approach is more flexible.

Map Collection:
|–hashtable: The underlying is a hash table data structure that is thread-synchronized. You cannot store null keys, null values.
|–hashmap: The underlying is a hash table data structure that is not synchronized by threads. You can store null keys, null values. Replaced the Hashtable.
|–treemap: The bottom layer is a two-fork tree structure that allows you to sort the keys in the map collection in a specified order.

Map Collection storage and collection are very different:
Collection one element at a time; map saves a pair of elements at a time.
Collection is a single-column collection;
A pair of elements stored in a map: A key, a value, and a corresponding (mapping) relationship between the key and the value.
Features: To ensure the uniqueness of the keys in the map set.

1, Add.
Put (Key,value): When the stored key is the same, the new value replaces the old value and returns the old value. Returns NULL if the key is not duplicated.
void Putall (MAP);
2, delete.
void Clear (): Empty
Value Remove (key): Deletes the specified key.
3, Judge.
Boolean IsEmpty ():
Boolean ContainsKey (Key): Contains key
Boolean Containsvalue (value): Whether the value is included
4, remove.
int size (): Return length
Value get (key): Gets the corresponding value by specifying the key. If NULL is returned, you can tell that the key does not exist. Of course there is a special case, that is, in the HashMap collection, the null key can be stored in the null value.
Collection values (): Gets all the values in the Map collection.
5, want to get all the elements in the map:
Principle: There is no iterator in map, collection has an iterator, and as long as the map collection is turned into a set set, an iterator can be used. The reason why the set is transferred is because the map set has the uniqueness of the key, in fact, the set set is derived from the Map,set set at the bottom of its practical is the map method.

★ The method of turning the map collection into set:
Set KeySet ();
Set EntrySet ();//The mapping of keys and values.
Entry is the internal interface in the map interface;
Why do you define it inside a map? Entry is the access to the key-value relationship, the gateway to the map, and the access to the key-value pairs in the map.

Remove all elements in the map collection by one: KeySet () method.
The keys in the map collection can be removed and stored in the set collection. Iterates over a set set. The iteration is completed, and the obtained key is obtained by the Get method.

        Set keySet = map.keySet();        Iterator it = keySet.iterator();        while(it.hasNext()) {            Object key = it.next();            Object value = map.get(key);            System.out.println(key+":"+value);        }

The way to take out all the elements in the map collection two: The EntrySet () method.

set  entryset = Map.entryset  ()         Iterator it = Entryset.iterator  ()  while (It.hasnext  ()) {Map me = (map) It.next  ()  System.out  .println  (Me.getkey  () + "::::"  +me .getvalue  ())  }

Tips for using collections:
See array is the structure of arrays, there is a corner mark, query fast.
See link is the linked list structure: The deletion speed is fast, and there are unique methods. AddFirst; addlast; Removefirst (); Removelast (); GetFirst (); GetLast ();
See hash is a hash table, you want to hash value, it is necessary to think of uniqueness, it is necessary to think of the elements deposited into the structure must cover the Hashcode,equals method.
See tree is a binary tree, it is necessary to think of a sort, you want to use the comparison.
Two ways to compare:
One is comparable: Cover CompareTo method;
One is comparator: Overrides the Compare method.
Linkedhashset,linkedhashmap: These two sets ensure that the hash table is stored in the order and in the order in which it is fetched.

When does the collection work?
When storing an element, use collection. The map collection is used when there is a mapping between the stored objects.

Guaranteed to be unique, use set. Not guaranteed to be unique, use list.

Collections: Its presence provides more functionality to the set operation. This class does not need to create objects, and internally provides static methods.
static method:
Collections.sort (list);//list sets the natural ordering of elements.
Collections.sort (List,new Comparatorbylen ());//Sort by the specified comparer method.

class ComparatorByLen implements Comparator<String>{    publicint compare(String s1,String s2){        int temp = s1.length()-s2.length();        return temp==0?s1.compareTo(s2):temp;    }}

Collections.max (list); Returns the element with the largest dictionary order in the list.
int index = Collections.binarysearch (list, "zz");//binary lookup, returns the corner label.
Collections.reverseorder ();//reverse-reverse sort.
Collections.shuffle (list);//random displacement of the position of the elements in the list.

To convert a non-synchronous collection to a synchronous collection: XXX synchronizedxxx (XXX) in collections;
List synchronizedlist (list);
Map Synchronizedmap (map);
Principle: Define a class that adds all the methods of the collection to the same lock and returns.

The difference between Collection and collections:
Collections is a Java.util class, a tool class for a collection class that provides a set of static methods for operations such as finding, sorting, replacing, threading, and converting non-synchronized collections to synchronous.
Collection is a Java.util interface, which is the parent interface of various collection structures, and the interfaces that inherit from it are mainly set and list, providing some operations on the set, such as inserting, deleting, judging whether an element is its member, traversing, etc.

Arrays:
The tool class used to manipulate array objects is a static method.
Aslist method: Converts an array into a list collection.
String[] arr = {"abc", "KK", "QQ"};
List List = Arrays.aslist (arr);//convert arr array to list collection.
What are the benefits of converting an array into a collection? Using the Aslist method, the array is transformed into a set;
The elements in the array can be manipulated through the methods in the list collection: IsEmpty (), contains, indexOf, set;
Note (limitations): Arrays are fixed length, can not be used to add or delete objects, etc., can change the length of the array function method. such as add, remove, clear. (The report does not support operation exception unsupportedoperationexception);
If the reference data type is stored in an array, the elements directly as a collection can be manipulated directly with the collection method.
If the base data type is stored in the array, Aslist will present the array entity as a collection element.

Set of variable groups: using the method in the collection interface: ToArray ();
If the data length of the specified type passed to ToArray is less than the size of the collection, then the ToArray method automatically creates a data of that type, and the length is the size of the collection.
If the length of the array that is passed the specified type is greater than the size of the collection, then the ToArray method does not create a new array, directly uses the array, and stores the elements in the collection in the array, and the other is the default value NULL for the location of the stored element.
Therefore, the best way to pass an array of the specified type is to specify an array of equal length and size.
What are the benefits of turning a collection into an array? Limit the additions and deletions to the elements in the collection, as long as you get the elements.

Jdk5.0 new Features:
Collection after jdk1.5, there is a parent interface iterable, the interface of the appearance of the iterator method to extract, improve the extensibility.

Enhanced for Loop: foreach statement, foreach simplifies iterators.
Format://enhanced for loop two arguments are written in parentheses, the first one is declaring a variable and the second is the container that needs to be iterated
for (element type variable name: Collection collection & Array) {
...
}

the difference between the advanced for loop and the traditional for loop:
When using the advanced for loop, it is necessary to explicitly target the traversal. This target can be a collection collection or an array, and if you traverse the collection collection, you also need to manipulate the elements during traversal, such as deleting, using iterators.
If you are iterating through an array, you also need to operate on the arrays elements, and it is recommended that you use a traditional for loop because you can define a corner label to manipulate elements. If only for traversal fetching, it can be simplified into an advanced for loop, which appears in order to simplify writing.

Can the advanced for Loop traverse the map collection? No. However, you can turn the map into a set and then use the foreach statement.

1), function: Iterate over the container of the storage object: Array Collection map
2), enhanced for loop iteration Group:
String [] arr = {"A", "B", "C"};//the static definition of the array, try only when the array is first defined
for (String S:arr) {
System.out.println (s);
}
3), single-column collection Collection:
List List = new ArrayList ();
List.add ("AAA");
Enhanced for loop, does not use a generic collection can I use an enhanced for loop iteration? Yes
for (Object obj:list) {
string s = (string) obj;
System.out.println (s);
}
4), double-row set Map:
Map map = new HashMap ();
Map.put ("A", "AAA");
Traditional way: Must master this way
Set Entrys = Map.entryset (); 1. Get all key-value pairs entry objects
iter = Entrys.iterator (); 2. Iterate through all entry
while (Iter.hasnext ()) {
Map.entry Entry = (Entry) iter.next ();
String key = (string) entry.getkey (); Get key and value separately
String value = (string) entry.getvalue ();
SYSTEM.OUT.PRINTLN (key + "=" + value);
}
Enhanced for loop iterations: In principle, the map collection cannot be iterated using the enhanced for loop, because the enhanced for loop can only iterate over the collection that implements the Iterable interface; iterable is the newly defined interface in Jdk5, a method iterator method, Only classes that implement the Iterable interface are guaranteed to have a iterator method, and Java has this qualification because it is enhanced internally by the For loop or by iterators, and in fact, we can use the enhanced for loop in some way.
For (Object Obj:map.entrySet ()) {
Map.entry Entry = (Entry) obj; Obj in turn represents the entry
System.out.println (Entry.getkey () + "=" + Entry.getvalue ());
}
5), set iterative attention to the problem: in the Iterative collection process, the collection can not be added or deleted (will be reported concurrent access exceptions); The method of the iterator (subclass Listiterator: The method of adding and deleting).
6), Enhanced for loop Note: When using the enhanced for loop, the element cannot be assigned;
Int[] arr = {A-i};
for (int num:arr) {
num = 0; Cannot change the value of an array
}
System.out.println (arr[1]); 2

Variable parameters (... ): Used in the parameters of the function, when the number of elements of the same type to be manipulated is not deterministic, but in this way, this parameter can accept any number of the same type of data.

Unlike the previously received array:
Before defining an array type, you need to first create an array object and pass the array object as a parameter to the function. Now, simply pass the elements in the array as parameters. The bottom layer is actually the encapsulation of these elements into arrays, and this encapsulation action, which is done at the bottom, is hidden. Therefore, the user's writing is simplified, and the action of the caller's definition array is less.
If a variable parameter is used in the argument list, the mutable parameter must be defined at the end of the parameter list (that is, the last argument must be, or the compilation will fail.) )。
What if you want to get multiple int numbers? You can use to encapsulate multiple int numbers in an array, and then sum the arrays directly.

Static import: All static members in the class are imported, simplifying the writing of static members.
Import static java.util.collections.*; All static members in the collections class have been imported

Some understandings of the collection framework

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.