On the Java Collection framework

Source: Internet
Author: User

                                  

?? Collection

There are two sub-categories under collection, List and set, respectively. The list is ordered and the elements can be duplicated. The set is unordered, and the element is not repeatable. Here is the concept of order and disorder, that is, the order of deposit and the order of removal is consistent, if consistent, is ordered, otherwise unordered.

List?

There are two sub-categories under List, respectively? ArrayList and LinkedList. ArrayList query fast, insert slow. LinkedList query slow, insert fast. We usually consider using LinkedList because the query in the set operation is more common than the update, and when you cannot choose which one to use, select LinkedList.

Arraylist?

? ArrayList is based on the array structure. Here we have to mention the contains method of ArrayList, which implements the Equals method at the bottom. ArrayList to compare two elements for equality (where the element refers to a reference data type), the instance template (class) of the element must re-use the Equals method, where it writes its own specific comparison. ArrayList has its own fetch method get (int index). At the same time collection extracts the common method of its subclasses iterator (), but this has limitations, in the iterative process can not be added to the collection and update operations. To break this limitation, List has its own unique iterator Listiterator (iterator subclass), which can be added or updated to the collection during the iteration.

The following code is implemented to exclude duplicate elements:

1  Public classArrayListTest2 {2      Public StaticArrayList singleelement (ArrayList al) {3ArrayList newal=NewArrayList ();4Iterator it =al.iterator ();5          while(It.hasnext ()) {6Object obj =It.next ();7             if(!newal.contains (obj)) {8 newal.add (obj);9Person p =(person) obj;TenSystem.out.println (P.getname () + "age" +p.getage ()); One             } A         } -         returnNewal; -          the     } -      -  Public Static voidmain (String [] args) { -ArrayList Al =NewArrayList (); +Al.add (NewPerson ("jospe01", 21)); -Al.add (NewPerson ("Jospe02", 22)); +Al.add (NewPerson ("jospe03", 23)); AAl.add (NewPerson ("Jospe02", 21)); at      -Iterator it =al.iterator (); -      -Al=Singleelement (AL); -      -      in}
 Public Boolean equals (Object obj) {        ifinstanceof person ))          return false ;                 =(person) obj;        System.out.println (this. name+ "..." +p.getname ());         return this. Name.equals (P.getname ()) &&age==p.getage ();    
Note: The Contains method is implemented at the bottom of the Equals method.
LinkedList

  LinkedList is based on the linked list structure. Here is a description of its unique approach: Addfirst,addlast,removelast,removefirst. A reasonable use of the above method can be implemented in the queue and linked list. The queue is FIFO, first AddFirst, then Removelast. Stack is advanced after out, first AddFirst, then Removefirst.

The following is the detailed code for the implementation of the queue:

Import Java.util.linkedlist;public class Queuedemo {private LinkedList link; Queuedemo () {link =new linkedlist ();} public void Myadd (Object obj) {link.addfirst (obj);} Public Object Myget () {returnlink.removelast ();} public Boolean isNull () {returnlink.isempty ();} public static void Main (string[] args) {Queuedemo queue =new queuedemo (); Queue.myadd ("Java01"); Queue.myadd ("java02"); Queue.myadd ("Java03"), while (!queue.isnull ()) {System.out.println (Queue.myget ());}}}

All of the Linkdelist's methods on remove return the currently deleted element. However, the Remove method has its own flaw, and if linkelist is empty during deletion, the exception is thrown, so the new version of the JDK introduces the poll method instead of the previous remove method, and returns null if the collection is empty;

Set

The two sub-interfaces under set are HashSet and TreeSet respectively. HashSet is based on the hash table structure, and TreeSet is based on the binary tree structure.

HashSet

ArrayList determines whether two elements are equal depends on the Equals method, while HashSet determines whether two elements are equal to the hashcode and equals methods. So if you are using HashSet and you are saving a custom object to HashSet, the class must override the Hashcode method and the Equals method. When you create an instance object, the system calls Hashcode to assign a hash value to each instance object, and the hash value is different, so when you deposit the same element (custom object) into HashSet, the system will assume that you are depositing a different object, because the hash value is different. This is why custom objects must override the Hashcode method. When the Hashcode method is overridden, the Equals method is called when the hash value returned is the same. Also note that HashSet is dependent on the hashcode and equals methods for determining whether an element exists and is deleted.

TreeSet   

TreeSet can sort the elements, sorted by the data structure of the binary tree. To sort a custom object, the first way is to make the custom object itself comparable, specifically implemented as an interface comparable, overriding the interface's Comparreto method, in the way the method writes comparisons, noting that when the main elements are compared, Minor elements are also compared (the comparison method for minor elements is also CompareTo). Here is a small tip, if you want to let the elements in the order of storage, you can return 1 directly in the CompareTo method, the second way is to write their own comparator, let their own definition of the comparator implementation interface comparator, and then cover the compare ( Object o1,object O2) method.

The following is a comparison of string lengths:

1 classStringcomparatorImplementscomparator{2 3 @Override4      Public intCompare (Object O1, Object O2) {5         //TODO Auto-generated method stubs6         intnum1=o1.tostring (). Length ();7         intNum2=o2.tostring (). Length ();8         intnum=NewInteger (NUM1). CompareTo (NewInteger (num2));9         if(num==0)Ten             returno1.tostring (). CompareTo (O2.tostring ()); One         returnnum;  A          -}
Generic

Before you introduce a map, you have to talk about generics. It is designed to address security issues and is a type-safe mechanism. Here's a piece of code that explains the non-generic security issues:

List List =new ArrayList (); List.add ("AA"); List.add (one) ;

In the above code, the list adds the string type element and adds the integer element, which is not a problem when compiling, but it will be error when running. If a generic is added, the following code:

list<string> list =new arraylist<string>(); List.add ("AA"); List.add ("BB");

The element in the list is then forced to be of type string, and if you add other types of elements, you will get an error when compiling.

While generics also avoid the hassle of casting, the following code:

ArrayList al =new  ArrayList ();    Al.add (new person ("jospe01", +));    Al.add (new person ("Jospe02",));         =al.iterator ();          while (It.hasnext ()) {        =it.next ();         =(person) obj;        System.out.println (P.getname ()+ "of the Age is" +P.getage ()  );    }

In the iterative process, a custom type element must cast a type if it wants to use its own unique method. But if iterator also joins generics:

Iterator<person> =al.iterator ();

You do not need to cast the type.

Map

The two subcategories below the map are HashMap and TreeMap respectively. HashMap is based on hash table structure, TREEMAP is based on binary tree structure. Ma<k,v> is the object on which the key is mapped to a value. Use map when you need to query to a specific value object based on the key. Both list and set look for elements by traversing the collection, but the map does not, as long as you know the key, you can find the corresponding value.

HashMap

This is mainly about the way HashMap gets elements, and if you know the key of the element, you can get the element by means of the get (Object key) method. There are also two other ways to get the element HashMap. A set<k> keyset () that returns a view of the keys contained in this map Set . The specific application is the following code:

map<string,string> map =new hashmap<string,string> () map.put ("", "jospe01"), Map.put ("The", "JOSPE02"); Map.put ("jospe03"); Set<string> Keyset=map.keyset ();iterator<string> it =keyset.iterator (); while (It.hasnext ()) {String key = It.next (); String Value=map.get (key); System.out.println ("Key:" +key+ "value:" +value);}

Another method is set<map.entry<k,v>> EntrySet (), which returns a view of the mappings that this mapping contains Set . , the following code is used specifically:

map<string,string> map =NewHashmap<string,string>(); Map.put ("Jospe01", "the"); Map.put ("Jospe02", "the"); Map.put ("Jospe03", "the"); Set<map.entry<string, string>> entryset=Map.entryset (); Iterator<map.entry<string, string>> it =Entryset.iterator ();  while(It.hasnext ()) {Map.entry<string, string> me=It.next (); String Key=Me.getkey (); String value=Me.getvalue (); SYSTEM.OUT.PRINTLN (Key+":"+value); }

TreeMap

TreeMap is like TreeSet. You can sort the elements in two ways, one for the custom object to implement the interface comparable, overwriting the CompareTo method. The second is to create a comparator to implement the interface comparator, covering the Compare method. When you choose to use TreeMap or treeset, you should see if the element has a mapping relationship, and if so, select TreeMap.

Collections

Collections is a tool class that operates on collection , and the main method is BinarySearch, which searches the specified list for the specified object using a binary search method.

Arrays

Arrays is also a tool class that contains various methods for manipulating arrays, such as sorting and searching.

On the Java Collection framework

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.