CoreJava learning 4-Collection framework and List set

Source: Internet
Author: User

Collection framework and List set

The Collection framework contains a series of linear tables with different data structures to find tables...). It is used to save the structure of a group of data.

There are two self-Interfaces under Collection: List and Set.

The most important difference between List and Set is:

1) List can store the same element repeatedly, but Set cannot. Therefore, List is a repeatable Set, and Set is a non-repeatable Set.

2) List is an ordered Set, and elements can be used through indexes; Set is an unordered Set.

ArrayList and rule List are commonly used in a List.

Set contains HashSet and TreeSet.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1533143Q1-0.jpg "title =" map.jpg "/>

1. Common Collection methods

Int size (): returns the number of objects contained in the set.

Boolean isEmpty (): whether it is null, not null, but no element in it)

Boolean contains (Object o): whether to include the specified Object

Boolean clear (): clears the set.

Boolean add (E e): add an object to the set

Boolean remove (Object o): removes an Object.

Boolean addAll (Collection <? Extends E> c): add all the elements in the other set to the set.

Boolean removeAll (Collection <?> C): removes all the same elements from the set and from the other set.

Iterator <E> iterator (): returns the corresponding Iterator of the set.

Example:

List list1 = new ArrayList (); List list2 = new ArrayList (); List list3 = new ArrayList (); list1.add ("1"); list1.add ("2 "); list1.add ("3"); list2.add ("4"); list2.add ("5"); list3.add ("1"); list3.add ("2"); list1.addAll (list2 ); system. out. println ("list1" + list1); // {1, 2, 3, 4, 5} list1.removeAll (list3); // Delete the intersection part of the System. out. println ("list1" + list1); // {3, 4, 5}/** only retains the same elements as the given set elements, and deletes the remaining elements. Preserve the intersection part */list1.retainAll (list2); System. out. println ("list1" + list1); // {4, 5}



2. ArrayList and rule list

The List interface is a sub-interface of Collection. It is used to define the data structure of a linear table. It can be understood as an array for storing objects, but the number of elements can be increased or decreased dynamically.

The most common implementation classes of the List interface are ArrayList and List. The List interface is implemented using dynamic arrays and linked lists respectively.

We can think that their methods are logically the same, but they differ in performance. ArrayList is more suitable for Random Access, and sorted list is more suitable for insertion and deletion, you can ignore this difference when the performance is not particularly required.

1) ArrayList-List of Dynamic Array Implementation (automatic resizing/maintenance): You can quickly index the corresponding elements by subscript, but move more elements when deleting and inserting them.

2) Sort List-List implemented by the linked List: you only need to change the connection "pointer" during insertion and deletion.

Because we can add different objects at will, it is very convenient to add them, but it is easy to see "class styling exception" during the acquisition ".

When an element is obtained, all objects are obtained. If you want to convert them into actual classes, you need to shape them.

You need to judge before styling; otherwise, the styling exception ClassCastException will occur. We usually use a type of object.


3. List common methods

1) The toString () method overridden by ArrayList calls the toString () method of the object it contains in sequence, and the Point class also overrides its toString () method.

2) The List ins method of the List Implementation class is used to determine whether an object is contained in the set. The specific logic is to call the equals method of the object contained in the Set in sequence to compare with the judgment object, if yes, true is returned. Therefore, as for objects in the Set, the equals method should be properly rewritten. For Point, if the equals method is rewritten and the logic is x and y are all the same, true is returned, and list is returned. contains (p) returns true.

3) The remove method is also related to the equals method of the object in the collection. First, you can call the equals method to find the object and then delete it.


4. get and set methods based on the lower mark

In addition to the methods defined by Collection, List also defines a series of methods based on the data structure of linear tables.

1) get (int index) method to obtain the index elements in the set.

Note: This method is exclusive to the List and the returned Object is

2) Object set (int index, Object obj): replaces the element indexed as index in the given element set, and returns the replaced element.

3) add and remove methods are reloaded.

Add (int index, Object obj): inserts a given element into the index, and moves the element from the original position to the back of the line in sequence ).

Object remove (int index): deletes the elements at the specified index. Only the elements to be deleted are returned by this method.


17th,

5. List other common methods

List also provides indexOf and lastIndexOf methods similar to String for retrieving an object in the set. The judgment logic is: o = null? Get (I) = null: o. equals (get (I )))

1) int indexOf (Object obj): returns the index value of the element that appears in the set for the first time.

2) lastIndexOf (Object obj): returns the index value of the last element in the set.

You can also convert a set to an array:

3) toArray (): converts a set to an array. Here, the parameter only informs the set of the array type to be converted, and does not use the array we provide, so the length is not required.

The element in the set should be of the same type.

String [] array = (String []) list. toArray (new String [0]);


6. iterator

All Collection implementation classes implement their iterator method. This method returns an Iterator interface type object to implement iterative traversal of Collection elements.

The Iterator defines three methods:

Boolean hasNext (): determines whether there are elements behind the pointer and whether there are uniterated elements.

E next (): the pointer moves backward and returns the current element.

Void remove (): Delete the elements just returned from the original set.

Each time the next method is called, you can only call the remove Method once. This method deletes the elements returned by the next method.

In the iteration process, you cannot call methods such as remove of the set to delete elements. Otherwise, ConcrrentModificationException may occur.

Note:

For List, you can traverse through the get method based on the lower mark, while the iterator method is designed for the Collection interface. All classes that implement the Collection interface can use Iterator for iterative traversal. Example:

List list = new ArrayList (); list. add ("1"); list. add ("2"); list. add ("%"); list. add ("%"); list. add ("2"); list. add ("1"); Iterator it = list. iterator (); // instance iterator object while (it. hasNext () {// use the hasNext () method to determine whether there are still uniterated elements. String str = (String) it. next (); // call next to return the element if ("% ". equals (str) {it. remove ();/* each time the next method is called, The remove method can only be called once. This method deletes the elements returned by the next method. * During iteration, you cannot call methods such as remove of the set to delete elements. Otherwise, ConcrrentModificationException may occur. * /// List. remove (str); // error. An exception ***} System may occur. out. println (list); // output set after iteration // you can also use for Iteration/* for (Iterator iterator = list. iterator (); iterator. hasNext ();) {String str = (String) iterator. next (); System. out. println (str );}*/

The iterator requires that the elements of the set cannot be changed when it iterates on the element. For example, you cannot delete the elements by using methods such as remove of the set. Otherwise, ConcrrentModificationException may occur.


This article from the "beautiful life needs to carefully record" blog, please be sure to keep this http://huing.blog.51cto.com/1669631/1295003

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.