Java Collection Framework

zhaozj2021-02-16  71

Overview of Java Collection Frame (JCF: Java Collections Framework (on)

Kevin Original (Participation: 282, Expert): 2003-11-21 6:17 PM Updated: 2003-11-22 9:48 AM: 1.3 Read: 2946 times

Abstract: This article discusses the generation, change and development of Java container libraries, but there is no specific explanation how to use these class libraries, trying to help Java learners master Java's container libraries from history of its development and change. In addition, in this article, one of the new features joined in J2SE1.5, which is about to be released, will be discussed: generics, which will make the container more powerful. If you have a mistake in the article, please criticize.

First, the collection

Collection Theory is an important basic theory in modern mathematics. Its concepts and methods have penetrated into many mathematical branches and other natural science sectors such as algebra, topology and analysis, etc., which provide the foundation of these disciplines to change these disciplines. Computer science as a modern science because of its source of mathematics, many of the concepts of naturally come from mathematics, and a collection is one of them. If the generation of the aggregation is injecting new vitality and vitality to mathematics, then the collection concept in computer science has also injected new vitality and vitality. 1. What is a collection that is difficult to set a set of precise definitions in the collection, usually, a class of things with the same properties, can be called a collection. For example, all programmers programmed by Java, all Chinese, etc. Normally, there are two representations, one is a reference method, such as a collection A = {1, 2, 3, 4}, the other is a nature description method, such as a collection b = {x | 0

<100

And

X

Belong to integer}. The founder of the collection Theory, Condur, gave a lot of axioms and nature in the creation of a collection theory, which has become the basis for the application of the collection in other fields. This article is not a collection theory, so if you are interested in the collection, you can Refer to the relevant books.

2, what is the collection framework, what is the concept of collection, what is the collection framework? The collection framework is a unified standard architecture that is specified for the collection and operation collection. Any collection framework contains three blocks: an external interface, an interface implementation, and an algorithm for collections.

· Interface: That is, an abstract data type of a collection. The interface provides the possibility that let us separately operate separately.

· Implementation: The specific implementation of the interface in the collection framework. They are actually those that can be multiplexed.

· Algorithm: A method of completing a useful calculation on an object that implements an interface in a collection framework, such as finding, sorting, and more. These algorithms are usually polymorphic because the same approach can be different when implemented in the same interface. In fact, the algorithm is a reused function. If you have learned C , the standard template library in C (STL) You should be unfamiliar, it is a good example of well-known collection framework. 3, the collection framework What is the benefit of our programming?

· It reduces the hard work of programming. The collection framework allows you to focus on your program's important part of your program by providing useful data structure and algorithms, rather than to make the program to operate properly on low-level design. Through the simple interoperability between the unrelated API, you will prevent you to write a lot of code for adaptive objects or conversion code to federate these APIs.

· It improves program speed and quality. The collection framework improves your program speed and quality by providing high performance and high quality implementation of useful data structures and algorithms. Because the implementation of each interface is interchangeable, your program can easily adjust by changing an implementation. In addition, you will be able to freely from writing your own data structure, there is more time to focus on the quality and performance of the other parts of the program. · Reduce the hard work of learning and using the new API. Many APIs have natural storage and acquisitions for collections. In the past, there are some sub-APIs to help manipulate its collection content, so there is a lack of consistency between those special sub-APIs, you have to learn from zero, and it is easy to make mistakes when using . The emergence of the standard collection framework interface makes this problem.

· Reduce efforts to design new APIs. Designers and implementors do not have to redesign each time you create an API depends on the aggregate content, as long as you use the interface of the standard collection framework.

· Collection framework encourages software multiplexing. It is reused for new data structures that follow the standard collection framework interface. The same is true for an algorithm for operating an object that implements these interfaces. With these advantages, through reasonable use, it will become a powerful tool for programmers. However, from the perspective of history, most of the structures are quite complicated, and they give them a bad name of the very unreasonable learning curve. However, I hope that Java2's collection framework can shorten your learning curve, so you can quickly grasp it. An array in many senior languages ​​is actually a simple implementation of a collection, such as C, C , Pascal, and Java. One possible structure of the array in C is shown below: The array holds multiple values ​​of the same type, and its length is fixed when the array is created, and it cannot be changed after the establishment. If you need a storage structure that can dynamically change, the array is not suitable. At this time, the assembly framework has used it.

Second, the container library before Java1.2

In fact, Java is no complete collection frame before Java2. It only has some simple container classes that can be extended, such as Vector, Stack, HashTable, etc. The elements contained in the Vector can be obtained through a integer index value, and its size can be automatically added or reduced when adding or removing elements. However, the design of Vector has a lot of missing (hereinafter). Stack is a stack sequence of backward first out (LIFO), which has learned the data structure, and it is important that it is the first thing to be put out. HashTable is similar to the MAP in Java2, which can be seen as an associated or mapping array that can be associated with two or more unrelated objects, and the array is different from which its size can be dynamically changed. VECTOR's operation is simple, add an object by addelement (), remove it with Elementat (), you can also query the number size () of the currently saved object; another ENUMERATION class provides continuous operation vector Method, this can get an Elements () method in the Vector to acquire an ENUMERATION class, you can use a While loop to traverse the elements. Check if there is more elements in HasMoreElements (). Use nextelement () to get the next element. Enumeration's intention is that you can completely ignore the infrastructure of the container you want to traverse, just pay attention to your traversal method, which makes it possible to reuse the traversal method. Due to the power of this idea, it is reserved in Java2, but the specific implementation, method names and internal algorithms have changed, which is the Iterator and Listiterator class in Java2. However, the functionality of Enumeration is very limited, such as only one direction, can only be read, and cannot be changed. Another single element container is Stack, which is most commonly used by pressing and ejecting, and the last pressed element is first popped up. You can imagine a book box that only opens above, and finally put it in must be the first to get it, and the first thing to put it can only be taken out after all books, this feature is called backward first out ( LIFO). The usage of Stack in Java is also very simple, and there is PUSH () to press one element and pop up an element with POP (). However, its design is unable to understand, Stack inherits the vector without using a vector type to implement its function, the result is that Stack also has a vector behavior, that is, you can treat Stack as a vector Use, and this is nothing relationship with Stack's intention. This should be a big mistake of the container class library designer in Java1 (1.0 / 1.1), but also, these are considerable change views in Java2. HashTable is also a useful container library in Java1. Its basic goal is to achieve two or more objects. For example, when we say that we say that the US White House, it is the presidential office building in Washington, USA. Why is it possible to talk to the White House, the President's office building? This is the relationship between "American White House" and the President's Office Building. Originally "White House" is four ordinary words, but now has different meaning. In Java, we can define a String to define object variables of "American White House", defining object variables of a president building, which is the use of Hashtable. By using the Pub (Object Key, Object Value), the two objects are associated, and the value object associated with the key is obtained with the product when needed.

You can also query the index value of an object, and the like. It is worth noting that the GET method here is very different when implementing an object, and the GET method in the vector is very different. Find a key object in a HashTable is more fast than in a vector. This is because HashTable uses a hash table technology (there is a detailed explanation in the data structure), and there is a hash code obtained by Object's Hashcode () method in Java. Hashtable is using this. Hash realizes the quick lookup key object. Another major mistake in the Java1 container library design is that there is no tool for sorting the container. For example, you want to sort the objects in the VECTOR container in a dictionary order, you have to implement it. Although the container class library in Java1 is so simple, the Java programmer has saved a lot at the time of programming, and the container classes are also used in large quantities, and they are so-called, but they have no choice. It may be that Java has been in a beautiful jerk in its growth process, so its shortcomings are also ignored, but fortunately, in Java2, the container class library designer has made a big knife, which makes the previous poor design, so that Java Be more perfect. Overview of Java Collection Frame (JCF: Java Collections Framework (below)

Kevin Original (Participation: 282, Expert: 1090) Published: 2003-11-22 11:27 AM Updated: 2003-11-22 3:56 PM Version: 1.0 Read: 2533 times

Third, the container library in Java2

Since Java1.2, the Java version is collectively referred to as Java2, and the container class library in Java2 can be said to be an implementation of a true collection framework. Basically, it is fully redesigned, but the container libraries in Java1 have been reserved in new design, which is mainly to be compatible, when using Java2 development programs, try to avoid using them, Java2 collection The framework is fully able to meet your needs. One thing to remind is that in Java1, the container class library is synchronized, while the container class libraries in Java2 are non-synchronized, which may be the result of the performance efficiency. The collection framework in Java2 provides an excellent interface and class that makes programmers to operate into batch data or object elements. These interfaces and classes have a lot of APIs for abstract data types, and this is our commonly used and well known in the data structure. For example, Maps, SETS, LISTS, ARRAYS, etc. And Java is packaged with object-oriented design, which greatly disguised the burden on programmer programming. Programmers can also define higher-level data abstractions based on this collection framework, such as stack, queue, and thread security collection, etc. to meet their needs. Java2's collection framework, pumping it, mainly three categories: List, set and map. As shown below:

As can be seen from the figure, List and Sets inherit the Collection, while Map is singular. It may be impossible for Map alone, why not inherit the Collection? But think about it, this design is reasonable. A MAP provides access to Value stored in Map through Key, that is, its operation is paired with object elements, such as PUT () and get () methods, and this is a SET or LIST is not available of. Of course, you can get the set set or value of the key from a key in a keyset () method or values ​​() method. 1. The Collection interface provides a set of methods that operate into a batch object. The list of methods represented by UML is as follows: it provides basic operations such as adding, deleting. It also supports query operations if it is an empty ISEMPTY () method, and so on. In order to support the Collection independently, Java's collection framework gives an Iterator, which makes you can operate a collection without knowing what the specific implementation of this Collection is. Its function is similar to the enumeration in Java1, just more easily and use, and the function is also more powerful. When establishing a collection framework, Sun's development team takes into account some flexible interface to operate into a batch of elements, and the method of selecting the optional operation of the collection is put together with the basic method. . Because the implementation of an interface must provide the implementation of all the methods defined in the interface, this requires a way to let the caller know that the optional method it is calling is currently not supported. Finally, the development team chooses to use a signal, which is to throw a unsupportedOperationException, if you encounter an exception to the above in using a collection, it means that your operation failed, such as you You will get an exception of an exception that does not support operational exceptions when you add an element. When you implement a collection interface, you can easily throw unsupportoperationException in the method you don't want to use, this method is not currently implemented, and UNSUPPOPERATIONException is an extension of RuntimeException. In addition, Java2's container library has a mechanism for Fail Fast. For example, you are using an object to traverse an object in a container. At this time, another thread or process has modified the container, then use the next () method, there may be disastrous consequences, and this is you don't want to see At this time, it will trigger an exception of a ConcurrentModificationException. This is Fail-Fast. 2, the List interface makes a simple expansion of Collection, and its specific implementation is commonly used with ArrayList and LinkedList. You can put anything in a LIST container and take it out when you need it. ArrayList can see it from its name to be a class-like group form in the form of a class, so its random access speed is extremely fast, and the internal implementation of LinkedList is a linked list, which is suitable for frequent insert and delete operations in the middle of the linked list. Free choice can be free when specific applications. The previous Iterator can only travel forward, while Listiterator inherits the idea of ​​Iterator and provides a way to traverse LISTs. 3, the SET interface is also an extension of Collection, and when the List is different, the object elements in the SET cannot be repeated, that is, you can't put the same thing twice into the same SET container. Its usual implementation has a Hashset and Treeset class.

Hashset can quickly locate an element, but you put it in the HashSet to implement the havehcode () method, which uses the algorithm of the previous hash code. TreeSet will be stored in order, which requires you to be sorted, which uses two other practical class Comparable and Comparator provided by the collection framework. A class is sorted, it should implement the Comparable interface. Sometimes multiple classes have the same sorting algorithm, so you don't need to repeat the same sorting algorithm each separately, as long as the COMPARATOR interface is implemented. There are two very practical uses of common classes in the collection framework: Collectes and Arrays. Collections provides a very useful way for a Collection container such as sort, copy, lookup, and padding, and ArrayS is a similar operation for an array. 4, MAP is a container associated with key objects and value objects, and a value object can be a MAP, so that a multi-level mapping can be formed. For key objects, like SET, the key object in a MAP container is not allowed to repeat, which is to keep the consistency of the results; if there are two key objects, then you want to get the value object corresponding to the key object. There is a problem, maybe you get the value of the value you think, the result will cause confusion, so the uniqueness of the key is important, and it is also in line with the nature of the collection. Of course, in the process of use, the value object corresponding to a key may change, and the value object with the last modification corresponds to the key. There is no uniqueness for value objects. You can map any multiple keys to a value object, which will not happen (but the use of you may cause inconvenience, you don't know the value of the key you get to the value) . There are two commonly used implementations: HashMap and Treemap. HashMap also used the hash code algorithm for quick finding a key, TreeMap is stored in order, so it has some extensions, such as firstKey (), lastkey (), etc., you can also from Treemap Specify a range to obtain its sub-map. The association of the keys and values ​​is very simple. You can associate a key with a value object with a Pub (Object Key, Object Value) method. Use GET (Object Key) to obtain a value object corresponding to this KEY object. Four, future Java container library

The previous sections discussed the past and the current situation of the Passer class library in Java, but SUN has begun to distribute the J2SE1.5 Alpha test version through some way. At this year's Javaone conference, many masters depict some new features of Java's beautiful future and in the next version, which is an important feature that is joined for the container class library is a generic. In fact, the generic is not new, there is already an object-oriented language, such as C . The basic goal of generics is simple: you can guarantee that you use a type of safe container. So how do you have a type of security? Let's first look at this code that does not use generic characteristics: import java.util. *; Public class generics {/ ** * Output a list of string types, assuming all elements in the parameter list are String. * / Public static void printlist (list list) {for (int i = 0; i

System.out.println ((String) List.get (i)). TOSTRING ());

}

}

public

Static

Void main (string [] args) {

List list = new arraylist ();

FOR

INT i = 0; i <9; i ) {

List.add

Number: " Integer.Tostring (i));

}

//list.add(new generics ()); // (1)

Printlist (list);

}

}

The above code is very simple, defined a static method to print a List for a String type, however, if you see, if you try to remove the comments in the (1), you will get a ClassCastException. Exception, because PrintList transforms each element in the list to String, and when you encounter the last element, it is found that it is a generics type, which is unable to complete the transformation, and exception is thrown. This situation is easy to appear in Java programming because Java's container class libraries typically save the object type, which is a direct or indirect hyperclass of all classes, which allows you to add any type of element to a list. Instead of giving you any prompts, experienced programmers may write a container class to limit the elements added thereto, which is a programming skill. But now we don't have to do that, the generic mechanism will do this for us. Then look at the improvements to the above code: import java.util. *; Public class generics {/ ** * Output a list of string types, limit all elements in the parameter list for String * / Public static void printlist (ArrayList

List) {

FOR

INT i = 0; I

System.out.println (List.get (i) .tostring ());

// Get ()

The return is no longer object type, but string type}} public static void main (string [] args) {ArrayList List = New ArrayList

();

//

Note the change in the grammar in this line for (int i = 0; i <9; i ) {list.add ("Number:" integer.tostring (i)); // can only add string type to it} List .add (new generics ()); // cannot pass, compile error printlist (list);}} As seen in the code, the declaration of the container has changed, ie after a container class is used back <> Explain that you want to put into the element type in this container, then you can only add that type to this container, otherwise compile cannot pass. The trouble of transformation is also saved in PrintList. Of course, there is a generic, not to say that the previous statement cannot be used, you can use the previous method, this is not any problem. In fact, according to the enhancement of the FOR statement function in JSR, it will be more simple to traverse a container. Of course, the generic use method is not only the case, and there is no complete description of it. I just want to tell you that generics have a convenient to program our programming, but still need to learn and master. As Java is further improved, its function and ease of use are also improved. I have reason to believe that Java's position will be more secure in the computer language, let people love Java love it more. I wish Java all the way!

转载请注明原文地址:https://www.9cbs.com/read-16887.html

New Post(0)