Basic knowledge:
What is a collection?
A collection is a container. Put multiple objects into the container. There is a water cup, you can choose to keep the water into the inside, you can also choose to pack milk. But you can't mix two different things to fit a cup. The collection of this container must be the same type of thing. (reference type, cannot be base type)
See this introduction, we may think of arrays, arrays are required to be stored inside the structure of a data type.
But what are the differences between arrays and collections ?
The size of the array is fixed, and the size of the collection is theoretically not qualified.
The elements in the array can be basic types or reference types. Collections can only place reference types.
Are the main members of the collection family (pictured from Baidu)
As the diagram shows, thecollection interface and the map interface are two bosses. The collection interface is then born with a set interface (unordered), a list interface (ordered), and a queue interface. The map interface holds data that has a mapping relationship. The sub-categories in the map have a common feature is that the data are key-value. For example, language-80, math-78, the subject is not repeatable, the score can be duplicated, so the key in the map cannot be duplicated, value can be duplicated. You need to check the score (value) and take it from the account (Key).
Specific implementation classes, commonly used are ArrayList, LinkedList, HashSet, Linkedhashset, HashMap, Linkedhashmap and so on, mainly divided into the following three categories
From the known, the set set is unordered and can only be accessed based on the elements in the collection itself.
The list collection is ordered and can be accessed through the index.
The Map collection accesses value through the key of each element.
The following is a list of methods under the collection interface
For a glance, these methods are nothing more than adding objects, removing objects, judging whether the collection is empty, emptying the container, and so no memory is needed.
The point of the method value is that when you need to convert the set element to an array of elements using object[] ToArray (), there is a trap: note the annotation section, the array cannot be directly (string[]) so that the variable is forced to transform, Only when you use the Convert element to string,
First look at the description of these two methods of list:
Object[] ToArray (): Returns an array (from the first element to the last element) that contains all the elements in the list in the appropriate order.
<T> t[] ToArray (t[] a): Returns an array of all the elements in the list in the appropriate order (from the first element to the last element); The run-time type of the returned array is the run-time type of the specified array
New Arraylist<string>(); Arr.add ("a"); Arr.add ("B"); Arr.add ("B"); // You can add duplicate objects // string[] str = (string[]) Arr.toarray (); // Error
object[] obj = Arr.toarray ();//First method
string[] obj1 = Arr.toarray (new string[3]);//The second method
Db.query () The second is a number of indeterminate parameters, and multiple parameters can be passed in as an array. List collection-to-array example
/** * Package preprocessing parameters parse and execute query @param sqlid @param param @ return * /public <T> list<t> query (String sqlid, map<string, object> param) { linkedlistnew linkedlist<object>(); = getsqlbybeetl (sqlid, param, paramvalue); return db.query (SQL, Paramvalue.toarray ()); }
Add Getsqlbybeetl If you need a map in SQL, refer to the following:
/*** Verify that the encoding is present *@paramOperatorid *@paramtype *@returnBoolean * Description: Operatorid is empty when new role group, Operatorid value when modifying role group*/ Public Booleanvaliqbgjxwcqkxxno (String qbgjxwcqkxxno, String type) {Map<string, object> param =NewHashmap<string, object>(); Param.put ("Column", jxwc.column_qbggyzfqkxxno); Param.put ("Table", Jxwc.table_name); String SQL=getsqlbybeetl (jxwc.sqlid_select, param); List<Jxwc> list =Jxwc.dao.find (sql,qbgjxwcqkxxno); intSize =list.size (); if("Add". Equals (Type) { if(Size = = 0){ return true; } }Else{ if(Size <= 1){ return true; } } return false; }
The collection interface isList,set,queue InterfaceParent interface, so the collection graph method can operate on these three collections. Itertor interface
Look at the set of the main member diagram that Itertor interface is not on the diagram, but he is also a member of the collection framework, but it with the Map collection series, C
Unlike the Ollection collection series, it is mainly loaded with elements that traverse the collection collection. The Itertor object is also called an iterator, which relies on the collection object to exist. Provides a unified programming interface for traversing collection.
The Main method:
Boolean Hasnext () returns True if the traversed collection has not finished traversing
Object Next () returns the next element in the collection
void Remove () deletes the last element returned by next ()
PackageTest01; Importjava.util.Collection;ImportJava.util.HashSet;ImportJava.util.Iterator; Public classTest { Public Static voidMain (string[] args) {Collection arr=NewHashset<>(); Arr.add (A); Arr.add ("B"); Arr.add ("C");//You can add duplicate objectsIterator Iterator =Arr.iterator (); while(Iterator.hasnext ()) {String Next=(String) iterator.next (); System.out.println (next); if(Next.equals ("C") ) {iterator.remove (); } Next= "Modify the value of the iteration variable to see if there is any effect";//Note the} System.out.println (Arr.tostring ()); }}
After running the discovery "attention", I wanted to change the elements in the collection without changing. So you get: iterator does not get the elements of the set itself, but instead gets the value of the element, so modifying the value of the iteration variable does not affect the collection itself.
Unlike other collections, iterator does not have the ability to load objects. If he does not rely on the collection exists, there is no value at all.
To delete a collection element, you must remove the element returned by the last next () by removing () iterator, and you cannot set your own remove (Object)
For example, you will find anomalies
PackageTest01; Importjava.util.Collection;ImportJava.util.HashSet;ImportJava.util.Iterator; Public classTest { Public Static voidMain (string[] args) {Collection arr=NewHashset<>(); Arr.add (A); Arr.add ("B"); Arr.add ("C");//You can add duplicate objectsIterator Iterator =Arr.iterator (); while(Iterator.hasnext ()) {String Next=(String) iterator.next (); System.out.println (next); if(Next.equals ("B") {arr.remove (next); } Next= "Modify the value of the iteration variable to see if it affects"; } System.out.println (Arr.tostring ()); }}
The exception is because the iterator uses the fast-fail principle (Fast-fail) and throws an exception as soon as the elements in the collection collection are found to be modified during the iteration. Occasionally found that if the code just changed to
if (Next.equals ("C")) { arr.remove (next); }
It's not unusual,----it's only possible to delete a particular element, but it shouldn't be risky.
foreach can also iterate through the collection, but notice that he does not get the collection element itself, but the system simply assigns the value of the collection element to the iteration variable, as well as the Java Concurrentmodificationexception exception that is thrown in the same ibid.
The following code (error demonstration)
PackageTest01; Importjava.util.Collection;ImportJava.util.HashSet;ImportJava.util.Iterator; Public classTest { Public Static voidMain (string[] args) {Collection arr=NewHashset<>(); Arr.add (A); Arr.add ("B"); Arr.add ("C");//You can add duplicate objects for(Object a:arr) {if(A.equals ("B") {arr.remove (a); } } } }
Set Set
It's like throwing objects at random into a jar, not remembering the order in which elements are added. Set a certain degree is collection, the method is not different, but the behavior slightly different, (do not allow repeating elements), if it is bound to add two elements of the same element, adding the failure adds () returns false;
Some of the above set similarities, Hashset,treeset,eunmset Three implementation classes are also featured.
Introduced in turn the next
Hashset
Judge the HashSet set of two objects equal, over two, equal () compare equal, the object's Hashcode () is also equal
Why do you have to compare the hashcode () of the object?
When a Hashset collection is collected into an object, the Hashcode () of the object is called to get its hashcode value to determine his storage location. Therefore, even if the equal () is equal to the two objects, hashcode different, stored in the HashSet location, can still add these two objects successfully.
Note: When loading an object into HashSet, if you want to override the Equals method, you also have to override the Hashcode method, because the two object hashcode equal to Equals () are the same.
question:hashcode () is it important for hashset?
A: The hash algorithm is quick to find the object being retrieved. Locates the storage location of objects in the collection through the hashcode of the object. Locate the element. In contrast, an array is the fastest array structure for storing a set of elements, and the array finds its members through an index that calculates where the element is stored in memory.
But why do you have an array and use HashSet? Arrays also have limitations, indexes are contiguous, and the length is immutable.
HashSet has a hashcode, so it can quickly locate objects and arbitrarily add objects.
Rewrite hashcode () note the Convention for Hashcode in Java.lang.Object:
When two objects are equal by Equals (), their hashcode should be the same.
The Hashcode method returned by the same object multiple times during the run of the program should be the same.
If two objects are not equal according to the Equals (Java.lang.Object) method, calling the Hashcode method on any of the two objects does not necessarily produce a different integer result. However, generating different integer results for unequal objects can improve the performance of the hash table. In fact, the Hashcode method defined by the object class does return different integers for different objects.
When you add a Mutable object to the HashSet, be aware that if the subsequent program modifies an instance variable of the Mutable object, it may cause him to be the same as the other elements in the collection, that is, two objects equals return True,hashcode. Causes HashSet to not manipulate those elements correctly.
Supplemental Understanding, Variable Object : after creation, the object's property value may change, that is, the hash value of the object after creation may be changed.
Example: The key of the object Mutablekey is created with the variable i=10 j=20, and the hash value is 1291. Then we change the value of the instance variable, and the key I and J of the object change from 10 and 20 to 30 and 40, respectively. Now the hash value of key has become 1931. Obviously, the key for this object has changed since it was created. So the class Mutablekey is mutable.
The following code is an example of a Mutable object added to HashSet.
As can be seen, after HashSet has added several members, modifying a member's instance variable will get the same member inside, so it is wrong.
However, for the last line, the member cannot be accurately accessed. A little doubt, to be solved.
PackageTest01;ImportJava.util.HashSet;ImportJava.util.Iterator;classmutclass{ Public intcount; PublicMutclass (intcount) { This. Count =count; } Public Booleanequals (Object obj) {if( This==obj) { return true; } if(obj! =NULL&& Obj.getclass () = = Mutclass.class) {Mutclass m=(mutclass) obj; return This. Count = =M.count; } return false; } Public inthashcode () {return This. Count; } PublicString toString () {return"Try Mutclass[count=" + Count + "]"; } } Public classTesthashset {@SuppressWarnings ("Unchecked") Public Static voidMain (string[] args) {HashSet Testhashset=NewHashSet (); Mutclass a=NewMutclass (3); Mutclass b=NewMutclass (1); Mutclass C=NewMutclass (-9); Mutclass D=NewMutclass (9); Testhashset.add (a); Testhashset.add (b); Testhashset.add (c); Testhashset.add (d); System.out.println ("First time" +testhashset); Iterator Iterator=Testhashset.iterator (); Mutclass First=(Mutclass) iterator.next (); First.count=9; /*Testhashset.remove (New Mutclass (3)); Testhashset.remove (b); The difference from the previous line*/System.out.println ("Second time" +testhashset); System.out.println (NewMutclass (-9) = =NewMutclass (-9)); System.out.println ("Fourth time" +testhashset.contains (NewMutclass (-9))); }}
HashSet cannot guarantee that the order of the added members is the same as its own order, but introduces a Linkedhashset subclass so that it can find his storage location by Hashcode and maintain the order of the added members, just like HashSet. The internal is implemented by a list of links, which has good performance when iterating through the collection.
Java Collection (top)