1, introduce the structure of collection frame
The collection is a very important knowledge point in Java, which is divided into three data structures: list, Set, Map and queue. Their structural relationships in Java are as follows:
The collection interface is the parent interface of list, Set, and queue.
The set interface has two common implementation classes: HashSet and TreeSet. The common interfaces of the list interface are ArrayList and vector interfaces.
The map interface has two common implementation classes: Hashtable and HashMap.
2. What interface to implement in collection framework
There are two ways to achieve comparisons: the first, the entity class implements the comparable interface (internal comparer). The second is to implement the comparator interface (external comparator).
First, implement the comparable interface:
Packagecom.chanshuyi.comparable;ImportJava.util.*; Public classStudentImplementsComparable<student> { PrivateString name; Private intAge ; PublicStudent () {} PublicStudent (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } @Override Public intcompareTo (Student o) {if(Getage () >O.getage ()) { return1; } Else if(Getage () <O.getage ()) { return-1; } Else { return0; } } //override ToString () for output PublicString toString () {return"[" + Name + "," + Age + "]"; } Public Static voidMain (String args[]) {Student S1=NewStudent ("Tom", 12); Student S2=NewStudent ("Marry", 9); Student S3=NewStudent ("Json", 88); List<Student> studentlist =NewArraylist<student>(); Studentlist.add (S1); Studentlist.add (S2); Studentlist.add (S3); Collections.sort (studentlist); System.out.printf ("Original Sort, list:%s\n", studentlist); }}View Code
Second, implement the comparator interface:
Define a student class first, without having to implement any interfaces.
Public classStudent {PrivateString name; Private intAge ; PublicStudent () {} PublicStudent (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; }}View Code
Define a comparer class to implement the comparator interface:
Public classStudentcomparatorImplementsComparator<student>{@Override Public intCompare (Student O1, Student O2) {if(O1.getage () >O2.getage ()) { return1; }Else if(O1.getage () = =O2.getage ()) { return0; }Else{ return-1; } } Public Static voidMain (String args[]) {Student Marry=NewStudent ("Marry", 12); Student Tom=NewStudent ("Tom", 3); Student Jackson=NewStudent ("Jackson", 88); Studentcomparator Comparator=NewStudentcomparator (); System.out.println (Comparator.compare (Marry, Tom)); //1System.out.println (Comparator.compare (Tom, Jackson));//-1 }}View Code
Thus, if you want the entity class to be sorted in the way you want it to be in the collection (if the collection supports it), then you need to implement the comparable interface for the entity class. If you simply want to compare the size of two entity classes and finally return a result, it is more appropriate to implement an external comparator with the comparator interface.
3. The difference between ArrayList and vectors
Both ArrayList and vectors implement the list interface, which is an ordered set, and the elements that are stored are allowed to be duplicated. Their bottom-level is implemented through an array, so the data structure of the list is fast, but the change of the speed and deletion is slow.
The differences between ArrayList and vectors are mainly in two areas:
First, thread safety. Vectors are thread-safe, and ArrayList are thread insecure. So if the collection data is only single-threaded access, then using ArrayList can improve efficiency. If you have multiple threads accessing your collection data, you have to use vectors because you want to keep your data safe.
Second, data growth. Both ArrayList and vectors have an initial capacity size, and they need to increase their storage capacity when the elements stored in them exceed their capacity. The ArrayList grows 0.5 times times the original, while the vector grows one more time. Both ArrayList and vectors can set the initial space size, and the vector can also set the amount of space to grow, while ArrayList does not provide a way to set the growth space.
4. The difference between HashMap and Hashtable
Both HashMap and Hashtable implement the map interface and are all KEY-VALUE data structures. Their differences are mainly in three areas:
First, Hashtable is a class of Java1.1, based on the stale dictionary class. And HashMap is an implementation of the map interface introduced by Java1.2.
Second, Hashtable is thread-safe, that is, threads are synchronized, and HashMap is thread insecure. This means that the hashmap should be used in a single-threaded environment, which is more efficient.
Third, HashMap allows null values as key or value, but Hashtable does not allow (throws NullPointerException).
5. What is the difference between List and Map?
This should be answered from two aspects, on the one hand, the data structure of list and map, on the other hand, the characteristics of storing data. In terms of data structure, the list stores a collection of single-column data, and the map stores a data collection of key and value types. In terms of data storage, the list stores data that is ordered and repeatable, while the data stored in the map is unordered and the key value cannot be duplicated (value values can be duplicated).
6, List, MAP, set three interfaces, access to elements, what are the characteristics of each?
The list and set have similarities, both of which are sets of single-column elements, so they have a common parent interface called collection. The set does not allow duplicate elements, so-called repetition, that is, there cannot be two equal (note, not just the same) object, that is, assuming that the set set has an A object, now I want to put a set set of a B object, but the B object is equal to equals to the A object, the B object is not stored in. Therefore, the Add method of the Set collection has a Boolean return value, when there is no element in the collection, when the Add method can successfully join the element, it returns True when the collection contains an element equal to the equals of an element, at which point the Add method cannot join the element. The returned result is false. When set takes an element, it is impossible to say the first number of elements, only the iterator interface to get all the element, and then iterate through each element.
The list indicates a sequential collection, noting that it is not sort by age, by size, by price, and so on. When we call the Add (OBJ-E) method multiple times, each time the object is added is like a train station to buy tickets in the same order as the queue, sorted by first served. Sometimes, you can also jump in the queue, that is, by calling the Add (int index,obj e) method, you can specify where the current object is stored in the collection. An object can be repeatedly stored in the list, each call to the Add method, the object is inserted into the collection once, in fact, not the object itself is stored in the collection, but in the collection with an index variable point to the object, when the object is add multiple times, That is, there are multiple indexes in the collection pointing to this object, as shown in X. List In addition to the iterator interface can get all the elements, and then iterate through each element, you can also call get (index i) to clarify the number of the first.
Unlike list and set, map is a set of two columns, with the Put method defined as follows: Put (obj key,obj value), each time it is stored, to store a pair of key/value, cannot store duplicate key, this repeating rule is equal to equals. You can obtain the corresponding value according to key, which is the value that the get (Object key) returns to key. In addition, all key combinations (Map.keyset ()) can also be obtained, together with all of the value (Map.values ()), and a collection of Map.entry objects (Map.entryset () that are combined with the key and value. )。
Lists hold elements in a particular order, and can have repeating elements. Set cannot have duplicate elements, internal ordering. Map holds the Key-value value, and value can be multivalued.
Java Collections common face questions Collection