Java Basics: Collections

Source: Internet
Author: User

Java Collection

1. Collection

Iterator interface:

2. List

An ordered Collection (also known as a sequence). Users of this interface can precisely control the insertion position of each element in the list. The user can access the element based on the integer index of the element (where it is located in the list) and search for the elements in the list.

Because the list is ordered, it adds the following methods relative to collection:

Add to:

void  Add (int index, e Element) // Insert the  specified element at the specified position in the list addall (intextends E > C) // Insert all elements in the specified collection into the specified position in the list

Delete:

E  Remove (int index, E Element) // Remove the element from the list at the specified position

Modify:

E  set (int index, E Element) // Replace the element at the specified position in the list with the specified element

To determine the index:

int  IndexOf (Object o)    // Returns the index of the first occurrence of the specified element in the list, or 1 int lastIndexOf If the list does not contain this element  (Object o )    // Returns the index of the last occurrence of the specified element in the list and returns 1 if the list does not contain this element

To take a subset:

List<e>  sublist (intint toindex)      // returns the FromIndex (included) specified in the list and Parts between Toindex (not included)

List iterators:

Listiterator<e>  listiterator ()     // Returns a list of elements in the list iterator (in the correct order)listiterator<e>  listiterator (int index)      // returns the list iterator (in the correct order) of the elements in the list, starting at the specified position in the list

Listiterator Interface:(the list-unique iterator is the sub-interface of the iteartor.) )

  Attention:

When you use the "1" method, a Java.util.ConcurrentModificationException exception occurs. This is because when the collection is iterated using iterator, it is not allowed to be modified by another thread, by other means. If you use the iterator method "2", the problem does not occur. And Listiterator is the response to this need, it can be in the iteration of the addition, modification and other operations.

1 Importjava.util.ArrayList;2 ImportJava.util.Iterator;3 ImportJava.util.ListIterator;4 5  Public classIteratortest {6      Public Static voidMain (string[] args) {7ArrayList arr =NewArrayList ();8Arr.add ("Hello--1");9Arr.add ("Hello--2");TenArr.add ("Hello--3"); One          AIterator it =arr.iterator (); -          while(It.hasnext ()) { -String str =(String) It.next (); the             if(Str.equals ("Hello--2")){ -Arr.add ("OK"); 1 -                 //It.remove (); 2 -                 //it.add ("OK"); 3 +             } -         } + print (arr); A     } at      -      Public Static voidprint (ArrayList arr) { -Iterator Iterator =arr.iterator (); -          while(Iterator.hasnext ()) { - System.out.println (Iterator.next ()); -         } in     } -}

  List includes ArrayList, LinkedList, Vector.

1) ArrayList and vectors are implemented based on the storage element's object[] array, supporting the use of small labels to access elements, while indexing data faster. However, when inserting elements, you need to move the elements in the container and perform slowly. Both have an initialized capacity size, when the stored element exceeds this size will dynamically expand, vector by default expanded to the original twice times (each expansion of the size of the space can be set), ArrayList 1.5 times times the original (no method to set the space expansion size).
2) The biggest difference between ArrayList and vector is Sybchronization synchronization, no ArrayList method is synchronous, and the majority of vectors are directly or indirectly synchronized (Add,insert,remove,set, Equals,hashcode, etc.). So vector is thread-safe, ArrayList is not. Therefore, the former performance is also slightly inferior to the latter.
3) LinkedList is implemented in a two-way list, the index of the data needs to be traversed from the head of the list, so the use of random access is slow, but the insertion and deletion efficiency is high.

  LinkedList: because it is implemented in a two-way list, it also adds the following methods, based on list:

Add to:

void  AddFirst (e o)    // Insert the given element at the beginning of this list void  addlast (e o)    //  Inserts the given element at the beginning of this list

Get:

E  getfirst (e o)    // return the first element of this list e  getlast (e o)    //  Returns the last element of this list

Delete:

E  removefirst (e o)    // Remove and return the first element of this list e  removelast (e o)    // Remove and return the last element of this list

 Attention:

Because Getfirst/getlast and removefirst/removelast do not have this element in the list, they throwNoSuchElementException。此时我们可以使用peekFirst/peekLast和poolFirst/poolLast方法。

E  peekfirst ()    // gets but does not remove the first element of this list, or nulle  peeklast ()     If this list is empty Gets, but does not remove, the last element of this list; returns nullE  poolfirst ()    // gets and removes the first element of this list if this list is empty If this list is empty, returns nullE  poollast ()    // gets and removes the last element of this list, or null if this list is empty

3. Set (hash set)

Set is a collection that does not contain duplicate elements, and the method is roughly the same as collection.

Its elements are unordered (inconsistent in the order in which they are deposited and taken out).

Operations are implemented through iterator.

1) HashSet

  The underlying data structure is a hash table.

The only way to ensure uniqueness is through the hashcode () and Equals () methods: If the hashcode value of the element is the same, then the Equals () method is used to determine the equality. If the element hashcode does not want to wait, the Equals () method is not called.

It is also implemented by the Hashcode () and the Equals () method for determining whether an element exists, and to delete an element.

Attention:

When you add a custom object to the HashSet collection, you need to override the Hashcode () and the Equals () methods.

2) TreeSet

The elements in the set collection can be sorted, and the underlying data structure is a two-fork tree.

The only way to ensure uniqueness is through the CompareTo () method, when return 0 represents equality.

There are two ways in which the TreeSet implementation is comparable:

1, one is to let the object itself implement comparable interface, and rewrite the CompareTo () method;

2, there is a custom comparator, but the comparator needs to implement the comparator interface, while overriding the Compare () method, and then can be added to the TreeSet initialization of the comparator;

3, when the two comparisons are present, the comparator shall prevail.

TreeSet  ts  =  new  TreeSet (new  mycomparator); class  Mycomparator  implements  comparator{...}

  

Java Basics: Collections

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.