First, The origin of the collection
In general, our program needs to know how many objects are created based on the Program's Runtime. But if the program is not running, the program development stage, We do not know exactly how many number of objects, and even do not know the exact type. In order to meet these general programming needs, we ask to be able to create any number of objects at any time and in any location, and what can these objects accommodate? We think of the array first, but the array can only put the uniform type of data, and its length is fixed, what to do? The collection was born!
Ii. what is a collection?
The Java collection class is stored in the Java.util package and is a container for storing objects.
Note: ①, Collections can only hold Objects. For example, you save an int data 1 into the collection, in fact, it is automatically converted into an Integer after the deposit, each basic type in Java has a corresponding reference type.
②, collections hold references to multiple objects, and the objects themselves are placed in heap memory.
③, collections can hold different types, unlimited number of data types.
third, Java Collection Framework diagram
In the above class diagram, the real line border is the implementation class, such as arraylist,linkedlist,hashmap, and so on, the polyline border is abstract class, such as abstractcollection,abstractlist,abstractmap, and the point line
The border is the interface, such as Collection,iterator,list. The collections and Arrays in the lower right corner are two helper Classes.
Discover a feature, all of the above collection classes, have implemented the iterator interface, which is an interface for traversing the elements in the collection, consisting mainly of Hashnext (), next (), remove () three METHODS. One of its sub-interfaces
Linkediterator added three methods on its basis, namely add (), previous (), hasprevious (). In other words, if the interface is iterator first, then the elements in the collection can only be traversed backwards,
The traversed element is not traversed, usually the unordered collection is implemented by this interface, such as hashset,hashmap, while those elements of the ordered collection, the implementation of the general is the Linkediterator interface, the implementation of this interface collection
Two-way traversal can be done by accessing the next element through next (), or by previous () to access the previous element, such as Arraylist.
Another feature is the use of abstract classes. If you want to implement a collection class yourself, implementing those abstract interfaces can be cumbersome and a lot of Work. Abstract classes can be used at this time, and these abstract classes provide us with many
Out-of-the-box implementation, We just need to rewrite some methods according to our own needs or add some methods to implement the collection class we need, the workload is greatly reduced.
Iv. set of explanations
①,Iterator: iterator, which is the top-level interface of the Java collection (excluding the collection of map series, The map interface is the top-level interface of the map series Collection)
Object Next (): Returns a reference to the element that the iterator just crossed, the return value is Object, and it needs to be cast to its own desired type
Boolean Hasnext (): determine if there are any elements within the container that can be accessed
Void Remove (): Delete the element that the iterator just crossed
So in addition to the collection of map series, we can iterate through the elements in the Collection.
Note: we can trace back to the top-level interface of the collection in the source code, such as the Collection interface, and you can see that it inherits the class Iterable
well, Here's The difference between Iterator and iterable:
Iterable: exists in the Java.lang Package.
We can see that the Iterator interface is encapsulated Inside. So as long as the implementation of the Iterable interface class, you can use the iterator Iterator.
Iterator: exists in the Java.util Package. The core method next (), hasnext (), remove ().
Here we refer to a iterator implementation class ArrayList to look at the use of iterators: for the moment, regardless of what the List collection is, just look at the usage of Iterators.
1 //produces a List collection, typically implemented as ArrayList. 2List List =NewArrayList ();3 //Add three elements4List.add ("Tom");5List.add ("Bob");6List.add ("Marry");7 //construct an iterator for the List8Iterator it =List.iterator ();9 //iterating through an element through an iteratorTen while(it.hasnext ()) { oneObject obj =It.next (); a System.out.println (obj); -}
②,Collection: Parent interface for List interface and Set interface
Take a look at the use examples of the Collection collection:
1 //Here we will ArrayList the collection as the implementation class of the Collection2Collection Collection =NewArrayList ();3 4 //adding elements5Collection.add ("Tom");6Collection.add ("Bob");7 8 //Delete the specified element9Collection.remove ("Tom");Ten one //Delete all elements aCollection C =NewArrayList (); -C.add ("Bob"); - Collection.removeall (c); the - //detect if an element exists -Collection.contains ("Tom"); - + //determines whether the empty - Collection.isempty (); + a //iterating through the collection with an enhanced for loop at for(Object Obj:collection) { - System.out.println (obj); - } - //using iterators Iterator -Iterator Iterator =Collection.iterator (); - while(iterator.hasnext ()) { inObject obj =Iterator.next (); - System.out.println (obj); to}
③, List: ordered, can be repeated Collection.
Because the List interface is inherited from the Collection interface, The basic method is shown Above.
1. Three typical implementations of the List interface:
①, List list1 = new ArrayList ();
The underlying data structure is an array, the query is fast, the deletion is slow, the thread is unsafe, high efficiency
②, List list2 = new Vector ();
The underlying data structures are arrays, fast queries, additions and deletions, thread safety, low efficiency, and almost eliminated the Collection.
③, List list3 = new LinkedList ();
The underlying data structure is linked list, query slow, and delete fast, thread unsafe, high efficiency
How do you remember it? We can imagine:
An array is like a person standing in a row, to find a 10th person is easy, according to the number of people can be found Soon. But insertion, deletion is slow, to look at a location to insert or delete a person, the number of people behind will Change. of course, people who join or delete are always at the end of the same fast.
List is like holding hands in a circle of people, to find a 10th person is not easy, must from the first person a number of Past. But insert, delete Fast. When inserting, just untie the hands of two people and re-take the hand of the newly added Person. Remove the same truth.
2, in addition, the List interface traversal can also use the normal for loop to traverse, specify the location to add elements, replace elements and so On.
1 //produces a List collection, typically implemented as ArrayList2List List =NewArrayList ();3 //Add three elements4List.add ("Tom");5List.add ("Bob");6List.add ("Marry");7 //construct an iterator for the List8Iterator it =List.iterator ();9 //iterating through an element through an iteratorTen while(it.hasnext ()) { oneObject obj =It.next (); a //System.out.println (obj); - } - the //add an element at a specified place -List.add (2, 0); - - //replace element at specified place +List.set (2, 1); - + //gets the index of the specified object a intI=list.indexof (1); atSystem.out.println ("indexed as:" +i); - - //traverse: normal for loop - for(intJ=0;j<list.size (); J + +){ - System.out.println (list.get (j)); -}
④, Set: A collection that cannot be duplicated.
1, Set hashSet = new HashSet ();
HashSet: the order of elements cannot be guaranteed; not repeatable; not thread-safe; the collection element can be NULL;
For HashSet: if two objects return true through the equals () method, the hashcode values of the two objects should also be the Same. * When an element is deposited into the HashSet collection, HashSet calls the Object's hashcode () method to get the Hashcode value of the object and then determines the storage location of the object in hashcode based on the hashset value * if the two-element equals ( ) method returns true, but their hashcode () return values are not equal, HashSet will store them in a different location, but they can still be added successfully! 2, Set treeSet = new TreeSet (); TreeSet: orderly; * If you create a TreeSet object using the TreeSet () parameterless constructor, The class that requires the element to be placed must implement the comparable interface so that the null element cannot be placed in it *
must be placed in the same class of objects. (sort by Default) or a type conversion exception may Occur. * Two objects compare size by the return value of the comparable interface CompareTo (object Obj) method, and in ascending order * when you need to put an object into TreeSet, overriding the Equals () method for that object, you should ensure that the The CompareTo method has consistent results with the object obj method * Custom Ordering: the implementation class that is passed in to the Comparator interface when the TreeSet object is Created. Requirement: The return value of the Compare method of the Comparator interface and the Equals () method of two elements have a consistent return value
Understanding of Java collections (continuous updates ...) )