List of Java collection frameworks

Source: Internet
Author: User

1. First introduce the collection framework:

Java, a programming language introduced by Sun Company in 1995. Java-enabled HotJava browser (Java applet support) shows the charm of Java: Cross-platform, dynamic web, Internet computing. Since then, Java has been widely accepted and has driven the rapid development of the web, and common browsers now support Java applets. A collection framework is a uniform standard architecture that is defined for representing and manipulating collections . Any set frame contains three chunks of content: external interfaces, interface implementations, and algorithms for set operations .

Framework benefits reduce Design toil

The set-up framework provides useful data structures and algorithms that enable you to focus on the important parts of your program, instead of focusing on low-level design for the program to function properly. By using these simple interoperability between unrelated APIs, you are exempt from writing large amounts of code for adapting objects or converting code to federate these APIs.

Improve speed quality

The collection framework improves the speed and quality of your programs by providing high-performance and high-quality implementations of useful data structures and algorithms. Because the implementation of each interface is interchangeable, your program can easily be adjusted by changing an implementation. In addition, you will be freed from the drudgery of writing your own data structures, giving you more time to focus on the quality and performance of other parts of the program.

API drawbacks

Many APIs are inherently store-and-Fetch for collections. In the past, such APIs had some sub-APIs to help manipulate its collection content, so there was a lack of consistency between those special sub-APIs, and you had to learn from scratch and easily make mistakes when used. The advent of the standard set-frame interface solves this problem.

Reuse of collection Frames

New data structures that conform to the standard set framework interfaces are inherently reusable. The same is true for an algorithm that operates an object that implements these interfaces.

With these advantages, and through proper use, it becomes a powerful tool for programmers. Historically, however, most of the collection's structure is rather complex, giving them a bad reputation for creating a very irrational learning curve. However, hopefully Java2 's set-up framework will shorten your learning curve and quickly master it.
Arrays in many high-level languages are actually a simple implementation of collections, such as c,c++,pascal and Java. An array holds multiple values of the same type, and its length is fixed when the array is created and cannot be changed after it is established. If you need a storage structure that can be dynamically changed in size, the array will not fit, and the set frame will have its place .

2.ListCollection

The collection interface provides a set of methods for manipulating mass objects
It provides basic operations such as adding, deleting. It also supports query operations such as whether it is an empty IsEmpty () method, and so on. To support the independent operation of Collection, the Java Collection Framework gives a iterator that allows you to manipulate a collection without knowing what the specific implementation type of this collection is. Its function is similar to the enumeration in JAVA1, but it is easier to master and use, and more powerful. When setting up a collection framework, Sun's development team took into account the need to provide some flexible interfaces for manipulating the elements in batches, and for the simplicity of the design, to put together the methods and the basic methods of selecting the collections. Because the implementation of an interface must provide the implementation of all the methods defined in the docking port, this requires a way for the caller to know that the optional method that it is invoking is not currently supported. Finally, the development team chooses to use a signal that throws an unsupported operation exception (Unsupportedoperationexception), and if you encounter one of the above exceptions in using a collection, it means that your operation failed, For example, when you add an element to a read-only collection, you get an exception that does not support operations. When you implement a collection interface, you can easily throw unsupportoperationexception in the method you don't want the user to use to tell the consumer that this method is not currently implemented, Unsupportoperationexception is an extension of runtimeexception.
Another JAVA2 Container class library has a fail fast mechanism. For example, if you are traversing an object in a container with a iterator, and another thread or process modifies that container, then the next () method can have disastrous consequences, which you do not want to see, A Concurrentmodificationexception exception is thrown. This is fail-fast. Features of the collection
The following table shows all the functions of collection, which is what you can do with set and list (excluding methods that inherit from object automatically). (The list also has some additional features.) Map is not inherited from collection, so we will treat it differently.
Boolean add: Make sure that the container holds the parameter that you passed to it. If it is not added, it returns false. (This is an "optional" approach and will be explained later in this chapter.) )
Boolean AddAll (Collection): Adds all the elements contained in the parameter Collection. Returns True if the element is added.
void Clear (): Clears all the elements saved by the container. ("optional")
Boolean contains (object): Returns True if the container holds the parameter Object.
Boolean Containsall (Collection): Returns True if the container holds all the elements contained in the parameter Collection. Boolean isEmpty (): Returns True if no element is stored inside the container.
Iterator Iterator (): Returns a Iterator that can be moved between the elements of the container.
Boolean RemoveAll (Collection): Removes all the elements contained within the container Collection the parameters. If you delete something, it returns true. ("optional")
Boolean Retainall (Collection): Only the elements included in the argument Collection are saved (the concept of "intersection" in the set theory). Returns true if a change has occurred. ("optional")
int size (): Returns the number of elements contained in the container.
Object[] ToArray (): Returns an array containing all the elements in the container.
Object[] ToArray (object[] a): Returns an array containing all the elements in the container, and this array is not an ordinary Object array, it should be of the same type as the parameter array a (to do type conversion).
Note that there is no get () method that can be accessed randomly. This is because collection also includes set. The set has its own internal order (so random access is meaningless). So if you want to check the elements of collection, you have to use iterators.

Next I'll tell you about list, set, and map implementations, and I'll show you (with an asterisk) what kind of implementation you should use by default for each container.

The list interface is a simple extension of the collection
Its specific implementation classes are commonly used in ArrayList and LinkedList. You can put anything in a list container and take it out when you need it. ArrayList can be seen in its name as an array-like form of storage, so its random access speed is very fast , and LinkedList's internal implementation is a linked list , It is suitable for frequent insert and delete operations in the middle of a linked list . The application can be freely selected as needed.

The basic usage of list is quite simple. Although most of the time, you just use the Add () object, use Get () to fetch objects, use iterator () to get the iterator of this sequence, but list has some other useful methods.

List (interface)

: The most important feature of list is order ; it ensures that the elements are preserved in a certain order. (Note: The order here is that the order of storage is consistent with the reading order, not by size) The list adds a number of methods based on the collection to allow inserting and deleting elements in the middle of the sequence. (Recommended for LinkedList only.) List can make Listiterator objects, you can use it in addition to the middle of the list to insert and delete elements, but also with it in two directions to traverse the list.

arraylist*:

A list that is implemented with an array. Allows for fast random access, but it is slower to insert and delete elements in the middle of the list. Listiterator can only be used in reverse traversal ArrayList, do not use it to insert and delete elements, because compared to LinkedList, in the ArrayList with Listiterator system overhead is relatively high.

Example code:

Listnew ArrayList();for( int i=0;i<10//给数组增加10个Int元素List//..程序做一些处理List.RemoveAt(5);//将第6个元素移除for( int i=0;i<3//再增加3个元素  List.Add(i+9);
Vector

Vector operation is simple, by adding an object by AddElement (), using ElementAt () to remove it, you can also query the current number of saved objects size (); There is also a enumeration class that provides a way to continuously manipulate elements in the vector , this can be obtained by using the elements () method in the vector to get an object of the enumeration class, which can be traversed with a while loop. Use hasMoreElements () to check if there are more elements in it. Use Nextelement () to get the next element. The purpose of enumeration is to allow you to ignore the infrastructure of the container you are traversing, focusing only on your traversal method, which makes it possible to reuse the traversal method. because of the powerful function of this thought, it is preserved in Java2, but the method name and internal algorithm are changed, which is the iterator and Listiterator class in Java2. However, the function of enumeration is very limited, such as only in one direction, can only read but not change.

Sample code

Import Java. Util. Vector;Import Java. Util. List;Import Java. Util. Iterator;Import Java. Util. Enumeration;/** * @desc vector test function: Traverse vector and Common API * * @author Skywang */public class Vectortest {public static void main (string[] args) {//new vector vector Vec = new vector ();add Element VEC. Add("1");Vec. Add("2");Vec. Add("3");Vec. Add("4");Vec. Add("5");Sets the first element to a -Vec. Set(0," the");Will -"INSERT INTO section3Location VEC. Add(2,"+");System. out. println("VEC:"+VEC);(Sequential lookup) get -The index System. out. println("Vec.indexof (+):"+vec. IndexOf(" the"));(Reverse lookup) get -The index System. out. println("Vec.lastindexof (+):"+vec. LastIndexOf(" the"));Gets the first element of the System. out. println("Vec.firstelement ():"+vec. Firstelement());Get the first3Elements of System. out. println("Vec.elementat (2):"+vec. ElementAt(2));Gets the last element of the System. out. println("Vec.lastelement ():"+vec. Lastelement());Gets the size of the vector System. out. println("Size:"+vec. Size());Gets the total capacity of the vector System. out. println("Capacity:"+vec. Capacity());Get the vector's "first2"To" section4The "Elements of the System. out. println("Vec 2 to 4:"+vec. sublist(1,4));Traverse Vector enumeration ENU = VEC via Enumeration. Elements();while (ENU. hasMoreElements()) System. out. println("Nextelement ():"+enu. Nextelement());Vector Retainvec = new vector ();Retainvec. Add(" the");Retainvec. Add("+");Get the collection of "Vec" contained in "elements in Retainvec" System. out. println("Vec.retain ():"+vec. Retainall(Retainvec));System. out. println("VEC:"+VEC);Gets the String array that the VEC corresponds to string[] arr = (string[]) VEC. ToArray(New string[0]);for (String Str:arr) System. out. println("STR:"+STR);Empty the vector.        Clear () and removeallelements ()! Vec. Clear();Vec. Removeallelements();Determine if the vector is empty System. out. println("Vec.isempty ():"+vec. IsEmpty());}   }

Vector in addition to providing synchronization, it and ArrayList no difference, because it is thread-safe, so inefficient, Java recommends we try to use ArrayList.

Stack

Single-element container stack, the most commonly used operation is press-in and eject, the last element pressed into the first is ejected. You can imagine a bookcase, the last to put in the book must be the first to be taken, and first put in only after all the books to take out, this feature is called LIFO (LIFO). The use of stack in Java is also simple, with push () pressing an element and popping an element with pop (). However, its design is not understandable, the stack inherits the vector and does not use the vector as one of the element types to achieve its function, the result is that stack also has the behavior of the vector, that is, you can use the stack as a vector, And that has nothing to do with Stack's intentions. This should be counted as JAVA1 (1.0/1.1) in the Container class library designers a big mistake, fortunately, these in the Java2 have a considerable change of view.

Example code:

ImportJava.util.Stack;ImportJava.util.Iterator;ImportJava.util.List;/** * @desc Stack test procedure. Test usage of Common APIs * * @author skywang */ Public  class stacktest {     Public Static void Main(string[] args) {Stack stack =NewStack ();//Add 1,2,3,4,5 to the stack         for(intI=1; i<6;        i++) {Stack.push (string.valueof (i)); }//Traverse and print out the stackIteratorthroughrandomaccess (stack);//Find the position of "2" in the stack, and output the method returns the distance from the nearest occurrence of the stack to the top of the stack, and the distance of the top item in the stack is 1.         intpos = Stack.search ("2"); System.out.println ("The postion of 2 is:"+pos);//Pup stack top element, traverse StackStack.pop (); Iteratorthroughrandomaccess (stack);after the top element of the peek stack, the traversal stackString val = (string) stack.peek (); System.out.println ("Peek:"+val); Iteratorthroughrandomaccess (stack);//through iterator to traverse stackIteratorthroughiterator (stack); }/** * Traverse stack with quick access * /     Public Static void iteratorthroughrandomaccess(List List) {String val =NULL; for(intI=0; I<list.size ();            i++) {val = (String) list.get (i); System.out.print (val+" ");    } System.out.println (); }/** * Traversing the stack via an iterator * /     Public Static void Iteratorthroughiterator(List List) {String val =NULL; for(Iterator iter = List.iterator (); Iter.hasnext ();)            {val = (String) iter.next (); System.out.print (val+" ");    } System.out.println (); }}
Use of LinkedList

Make a stack with LinkedList
Stack is sometimes referred to as a "last in, first Out" (LIFO) container. That is, the last thing that is "pressed" into the stack will be the first to "bounce" out. As with other Java containers, everything that presses in and out is an object, so unless you use object only, you have to type-convert the things you bounce.
LinkedList method can directly realize the function of stack, so you can use LinkedList without writing stack.
If you only want the functionality of the stack, then inheritance is not appropriate, because inheriting a class that has all the methods of LinkedList.
Make a queue with LinkedList
A queue is a "FIFO" container. That is, you put something in one end and take it out from the other end. So the order in which you put things is the order in which you take things. LinkedList has a way of supporting queue functions, so it can also be used as queue.
It is also easy to make a deque (bidirectional queue) with LinkedList. It's like a queue, but you can add and remove elements from either end.

List of Java collection frameworks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.