Java collection summary

The Java collection framework provides a set of interfaces and classes with excellent performance and easy to use, including two interfaces: collection and map, which are located in Java Util package. The collection set contains two common subsets - list and set (1) the common subclass ArrayList vector of the list set (2) the common subclass HashSet TreeSet linkedhashset of the set set

Map collection and collection collection belong to parallel relationship, not inclusive relationship. Common subclass - HashMap treemap note: the interfaces and classes contained in the above collection framework belong to Java Util package, so you need to import the package when using.

Linked list structure is a linear data structure composed of multiple nodes, and each node contains data and references to the next node.

LinkedList is a collection class. It uses a linked list as its storage structure, which is easy to delete and add elements, but it is inefficient to query elements according to the index. Implementation class of linked list structure LinkedList ------ implementation class of linked list + hash table structure hashlinkedset LinkedList class introduction: (1) using linked list storage mode (2) disadvantages: low efficiency of traversal and random access to elements (3) advantages: high efficiency of inserting and deleting elements (however, the premise is that inefficient queries must be performed first. If inserts and deletions occur at the beginning and end, the number of queries can be reduced.) TreeSet is a collection class of collection type, in which the elements are unique, and the binary tree is used as the storage structure, and the elements are arranged in natural order. Set collection features: unordered and unique (no repetition) set collection subclass ----- TreeSet elements are orderly (natural order) the unique binary tree structure stores data ----- the HashSet elements are out of order, and the unique hash table structure stores data ----- the linkedhashset elements are in order (addition order) the unique linked list structure maintains order. If you want to put multiple objects of the user-defined class student into the set TreeSet, you can arrange all elements according to the natural order of an attribute, The student class is required to implement the comparable interface. In the previous Java classes, it can be found that many classes have implemented this interface, such as string integer, etc. The purpose is to compare objects. There needs to be a standard for comparing objects. This standard is to compare objects according to a certain attribute of the object. Custom classes, such as student class, exist as TreeSet collection elements. For comparison, this class needs to implement this interface, override the abstract method -- compareto() method in the comparable interface, and specify the comparison standard. In Java, the access time of map collection is nearly stable. It is a data structure of key value pair mapping. This data structure is implemented through an array. Note: key value pair storage structure set MapMap set: key – value mapping -- "key -- unordered and unique (set set set characteristics) -" value -- unordered and not unique (collection set characteristics) 8 The iterator iterator is born for a collection and specifically implements collection traversal. The interface has three methods: hasnext(), next(), and remove(). Traversal mode of the set: mode 1: directly output the set object mode 2: use for each or standard for loop -- > extension: the underlying principle of the for each statement is to use the iterator iterator mode 3: use iterator + while loop to traverse the iterator ------ iterator exists as an interface. There are only three methods in this interface: ---1 Hasnext() determines whether there are elements in the container / collection -- - 2 Next() gets the current element -- 3 Remove() removes element 1 The statement about Java collections in the following options is wrong (AC). (select two items) A. list interface and set interface are collections interface. There are two sub interfaces. B. the elements stored in list interface are orderly and not unique. C. the elements stored in set interface are disordered and not unique. D. map interface stores mapping information. Each element is a key value pair. Options a: collection interface, collections collection tool class, and both Essentially different. This option is incorrect. Option B: list set features: ordered, Not unique (elements can be repeated) option C: set set features: unordered, unique, this option is wrong. Option D: map set features: key value pairs, mapping relationship 2. The following java code, the output running result is (a). (select one) public class test {public static void main (string [] args) {list list = new arraylist(); list. Add ("STR1"); list. Add (2, "str2"); String s=list. get(1); Sy stem. out. println(s); }} A. there is an exception when running B. It runs correctly, output STR1 C. It runs correctly, and output STR2 d. There is an exception when compiling. The add (int index, object obj) method refers to adding elements at the specified location. Execute to list add("str1"); After that, the size of the element in this collection is 1, but the list is executed add(2,"str2"); When adding data to the position with subscript 2, it is found that the maximum subscript value is 1. How can elements be added at the position with subscript value 2? Therefore, the index out of boundary exception will occur. 3. The following java code is used to first store the contents of an array into the collection, and then judge whether there are specified elements in the collection, There are (d) errors. (select one) import java.util.list; public class test {public int getindexofarray (float [] f) {int RTN = - 1; float objf = 3.4; / / f or F list = null should be added after the decimal here; / / the array has only declarations and no instantiation. For (int i = 0; I al) {al. Add (2); Al = new arraylist(); al. Add (3); al. Add (4);} public static void main(String[] args) { List al = new ArrayList (); al.add(1); print(al); Sy stem.out.println(al.get(1)); }} A 1 B.2 C.3 D.4 1 add (object obj) method for adding elements 2 get (int index) obtain specific object analysis according to the index value 1 A1 in the main method is a local variable. Similarly, A1 in the print method is also a local variable 2. The scope of the local variable is only valid in the current method or code block. That is, A1, A1 in the main method Get (1) calls the list collection object in this method. It can't do anything about A1 in the print method! 5. In Java, the following collection types can store unordered The data that does not duplicate is (d). (select one) a ArrayList B. LinkedList C. TreeSet D. HashSet ArrayList order (addition order) is not unique (duplicate elements are allowed) ---- LinkedList order (linked list order) is not unique (duplicate elements are allowed to exist) ---- TreeSet order (natural order) is not unique (duplicate elements are not allowed to exist) ------Do not meet HashSet disorder and uniqueness - meet the requirements of question 6 The execution result of the following code is (c). (select one) set s = new hashset(); s.add("abc"); s.add("abc"); s.add("abcd"); s.add("ABC"); Sy stem. out. println(s.size()); A. 1 B. 2 C. 3 D. 4

Set set features: unordered + unique. If duplicate elements appear, they will only be added once in the set; Two of the four elements were found to be identical.

7. Given the following java code, the result of compiling and running is (c). (select one) public class test {public static void main (string [] args) {map = new hashmap(); string s = "code"; map.put (s, "1"); map.put (s, "2"); sy stem.out.println (map. Size());}} A. an error occurred during compilation B. an exception was thrown during runtime C. correct operation, output: 1 D. correct operation, output: 2 map set features: key value key value pair mapping relationship key requirements: unordered, unique value requirements: unordered, not unique if it is found that the keys are the same -- the values are different, then the last key value pair is used as the benchmark -- added to the set, To put it bluntly, an overwrite operation occurred. map. put(s,"1");---------- map. put(s,"2"); The above situation occurs in the two lines of code, so only one element, that is, map, can be added to the collection this time put(s,"2"); Therefore, the number of elements in the set is 18 The following collection classes are non thread safe, And the structure adopts hash table is (c). (select one) A. vector B. ArrayList C. HashMap D. hashtable retain thread safety -- hashtable -- attach importance to safety over efficiency: neither key nor value can be null. Non thread safety -- HashMap -- attach importance to safety and efficiency: key and value are allowed to be null, and the operation speed is higher than that of hashtable. In Java, LinkedList class and ArrayList class belong to collection framework class, as shown below (CD) options are methods that LinkedList class has but ArrayList class does not. (select two items) a add (object o) B. add (int index, object o) C. getfirst() D. removelast() ArrayList + LinkedList + vector all belong to subclasses of list collection. Common methods in the list set: add (object obj) add the element add (int index, object obj) to the set; Add an element to the specified location of the collection. According to the principle of subclass implementing the interface, there are also subclasses of methods owned by the interface, so option a and option B are excluded. Getfirst() gets the first element of the linked list and removelast() deletes the last element of the linked list. The above two methods are methods that LinkedList class has but ArrayList class does not. 3、 True or false 1 The elements in arrays and collections can be any data type, including basic types and reference types. ( × ) Array ---- it can be any type of array, including basic data type and reference data type. Set - only objects can be stored. Even if 1 is put in, it is also an object rather than the number 2 The set interface and list interface in a Java collection are derived from the collection interface. (√) set sets and list sets, both of which are commonly used subsets of collection sets. However, map sets and collection sets do not contain relationships. They are parallel relationships. 3. The collection interface stores a group of non unique and orderly objects. It has two sub interfaces: list and set( × ) Collection features: elements are out of order and not unique 4 Collection is the top-level interface of Java collection, in which the elements are unordered and unique. The Java platform does not provide any direct implementation of this interface. ( × ) Collection features: the elements are out of order and not unique. It is found that the expression of the question is wrong. 5. List is an ordered collection. Using this interface, you can accurately control the insertion position of each element. Users can use indexes to access elements in lists, which is similar to Java arrays. (√) add (int index, object obj) adds an element at the specified position. Get (int index) obtains the object corresponding to the index value in the set according to the index value. Description: the bottom layer of ArrayList collection uses arrays. 6. HashSet adopts hash table storage structure, which is characterized by fast query speed, but the elements are arranged in disorder. (√) such methods: the hash table stores elements, and the speed of adding, deleting and querying elements is very fast. Disadvantages: elements are disordered. 7. LinkedHashMap is an orderly HashMap, which has fast query speed and is convenient for adding and deleting operations. (√) the class with hash table storage structure has the advantages of very fast addition, deletion and query of elements. 8. The value of basic data type can be directly stored in vector object( × ) Instead of direct storage, you need to wrap the basic data types through the JVM, turn them into wrapper classes and store them in the collection. 9. Dictionary establishes the mapping between keywords and values. As long as a keyword is provided, dictionary will return a corresponding value. (√) the dictionary class is an abstract class used to store key / value pairs. Its function is similar to that of the map class. Given the key and value, you can store the value in the dictionary object. Once the value is stored, you can get it through its key. So, like map,

The public abstract class dictionary extensions objectdictionary class is any class that maps keys to corresponding values (such as hashtable). Each key and value is an object. In any dictionary object, each key is associated with at most one value. Given a dictionary and a key, you can find the associated element. Any non null object can be used as a key or value. Generally, you should use the equals method in the implementation of this class to Determines whether the two keys are the same. Note: These are outdated. The new implementation should implement the map interface, not extend this class. 10. Generics are javase 1 7, the essence of generics is parameterized type, that is, the data type operated is specified as a parameter. The advantage of introducing generics into the Java language is security and simplicity. ( × ) The generic type is jdk1 6, not javase 1 7 is jdk1 7 appear. 11. Collection is a tool class that specifically operates on collections. It provides a series of static methods to operate on various collections. ( ×) Collection is the interface type and the largest interface for storing single values; Collections is a tool class for manipulating collections. Just like arrays, arrays is an array tool class. 12. The iterator interface can traverse the implementation class of any collection interface, and the iterator () method can be used to obtain the iterator instance from a collection. Iterators replace enumeration in the Java collection framework. (√) for any type of collection, iterators can be used to traverse elements. There is an iterator () method in the collection collection, which can create iterator objects. Before the iterator, the enumeration iterator was used, but at this time it is obsolete and no longer used. 13. Use the enhanced for loop to traverse the list or set. If the list or set is not generic, it can also be traversed. (√) the format is as follows: for (data type variable name: array / set name) {sy stem.out.println (variable name);} Analysis: data type ----- what type of element is, here is what type of variable name ----- do not conflict with other variable names. Array / collection name ---- like arr or list. If the collection framework does not use generic restrictions, the element type is object by default. 14. On the premise that the class has overridden the equals and hashcode methods, equals returns true and hashcode must be equal. (√) the equals () method, which originally exists in the object class, represents the address value of the object in memory. However, in some cases, you cannot meet the requirements of subclasses (you want to compare the contents of objects), so you need to override this method. When overriding this method, the internal code has a comparison involving hash codes. 4、 Short answer 1 Comparison of set and array A: array is not object-oriented and has obvious defects. Set completely makes up for some shortcomings of array. It is more flexible and practical than array, which can greatly improve the development efficiency of software, and different set framework classes can be applied to different occasions. The details are as follows: 1. The array capacity is fixed and cannot be changed dynamically, and the collection class capacity changes dynamically. 2. 2: Array can store data of basic data type and reference data type, while collection class can only put data of reference data type. 3: The array cannot judge how many elements actually exist in it. Length only tells the array capacity; The set can determine how many elements actually exist, It doesn't care about the total capacity. 4: the set has a variety of data structures (sequential list, linked list, hash table, tree, etc.), a variety of characteristics (orderly and unique), and different applications (quick query, easy deletion and order), unlike arrays, which only use sequential table method. 5: collections exist in the form of classes and have the characteristics of encapsulation, inheritance and polymorphism. Various complex operations can be realized through simple method and attribute calls, which greatly improves the development efficiency of software. 2. Briefly describe the differences and relations among list, set, collection and map. Collection is a Java collection Combined with the top-level interface, it stores a group of non unique and unordered objects; Map set is a set for storing key value pairs. Features: key is unique and value allows repetition. List interface and set interface are collections interface, with two sub interfaces; The list interface stores a group of objects that are not unique and orderly (insertion order); the set interface stores a group of unique and unordered objects; the schema diagram of collection, list and set:

(1) List: 1) is an ordered collection. Using this interface, you can accurately control the insertion position of each element. Users can use the index to access the elements in the list, which is similar to Java arrays. 2) all methods that can operate the index are unique to the list interface. (2) set: 1) the interface stores a group of unique and unordered objects (the order in which data is stored and retrieved may not be the same). 2) the method of operating data is similar to that of list, and there is no index related method in the set interface. 3. The difference and relationship between ArrayList and LinkedList. What is their underlying implementation? A: ArrayList and LinkedList both implement the list interface, and both have the characteristics of orderly and non unique elements in the list. Order: Add order / insert order ArrayList implements variable length arrays and allocates continuous space in memory. The efficiency of traversing elements and random access elements is relatively high; LinkedList uses linked list storage. High efficiency in inserting and deleting elements 4 Does each object have a hash code? What is the hash code generated from? Will it repeat? A: Yes. Acquisition of hash code: the hashcode () method in the object class. The hash code of the same object will not be repeated. 5. HashSet adopts hash table as storage structure. Please explain the characteristics and implementation principle of hash table. Tip: explain its principle by combining hashcode() and equals() of object class 6 The difference and relationship between vector and ArrayList. A: the implementation principle and function are the same. They are array structures with variable length, which can be used mutually in many cases. The main differences between the two are as follows • vector is an early JDK interface, and ArrayList is a new interface instead of vector • vector is thread safe and inefficient; ArrayList emphasizes speed over safety and thread non safety • when the length needs to be increased, the vector will double by default and ArrayList will increase by 50% 7 Could you briefly describe the difference between HashMap and hashtable? A: the implementation principles and functions are the same. The underlying layer is a hash table structure. The query speed is fast and can be used mutually in many cases. The main differences between the two are as follows: hashtable is the interface provided by the early JDK, HashMap is the interface provided by the new JDK, hashtable inherits the dictionary class, HashMap implements the hashtable thread safety of the map interface, and HashMap thread is not safe. Hashtable does not allow null values, HashMap allows null value 8 What are the benefits of using generics? A: generics are Java se 1 5, the essence of generics is parameterized type, that is, the data type operated is specified as a parameter. The advantage of introducing generics into the Java language is security and simplicity. 9. What is the difference between collections and collections? A: collection is a collection interface provided by Java, which stores a group of non unique and unordered objects. It has two sub interfaces, list and set. There is also a collections class in Java, which is specially used to operate the collection class. It provides a series of static methods to realize the search, sorting, thread safety and other operations of various collections.

Object oriented and array deep links: https://pan.baidu.com/s/1edkknsEmus_qiw77w3YNtg Extraction code: qlqr

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>