Java Foundation (17), Collection Class (1:collection)

Source: Internet
Author: User

I. What is a collection class?

Two. Collection interface

2.1 Collection Sub-interface (list interface and set interface)

Common methods of 2.1 collection

Three. iterators (Iterator)

3.1 About Iterators

3.2 Iterations of its usage

3.3 Simplification of iterators: enhancing for loops

3.4 Using iterators to add elements to a collection

Four. List interface

Method of 4.1 list interface

Implementation class for the 4.2 list interface

4.3 List traversal method

4.4 Concurrency Modification exceptions

I. What is a collection class?

  Easy to operate on multiple objects, you need a container that can store objects, it has: 1, can be stored in different object types, 2, the length of the container variable (put how many objects in how much);

In the sauce ~ ~ Meet the requirements of the container is set, features such as ~

two. Collection Interface

Collection: The top-level interface of the collection frame. Represents a set of objects, also known as collection elements.

2.1 Collection Sub-interface

Collection has two sub-interfaces, and their features are:

List interface: Can hold duplicate elements, element access is " orderly ";

Set interface: Can not store duplicate elements, usually the element access is " unordered ", there are some implementation classes are " orderly ".

Note: The above mentioned " ordered, unordered " refers to whether the element is stored in the order in which it is stored and not " sorted " on the element.

2.2 Common methods in the collection interface "return type method name (formal parameter)"

Add action

    • boolean Add (Boject e): Make sure this collection contains the specified element (optional action).
    • Boolean AddAll (Collectiong c): Adds all the elements in the specified collection to this collection (optional operation).

Delete operation

    • void Clear (): Removes all the elements in this collection (optional action).
    • Boolean Remove (Object o): Removes a single instance of the specified element from this collection, if one exists (optional action).
    • Boolean Removaall (Collection c): Removes all elements in this Collection that are also contained in the specified Collection (optional action).

Query operations

    • int size (): Returns the number of elements in this collection

Judging actions

    • boolean isEmpty (): returns trueif this collection does not contain an element.
    • Boolean contains (Object obj): Returns trueif this collection contains the specified element.
    • Boolean containsall (Collection C): Returns trueif this Collection contains all the elements in the specified Collection.

Iterative operations

    • Iterator Iterator (): Returns an iterator that iterates over the elements of this collection.

three. iterators: Iterator

3.1 about iterators

Iterations are a way of extracting elements from a collection because there are iterator methods in collection, so each sub-class collection object has an iterator, and the next method of the iterator returns a value type of object, so remember the type conversion.

iterators read elements :

1     Collection C = new ArrayList ();    Create a Collection Object 2     Iterator it = C.iterator ();    Gets the iterator for this collection 3     while (It.haxnext ()) {        //Traverse this collection 4         Object o = It.next (); 5     }

  Description :

1, the iterator does not guarantee that the order of the elements taken and deposited in the same order, "some" is guaranteed by the set instance itself;

2, the iterator itself is an interface, the method returns an iterator instance object, usually using an interface polymorphism using an iterator;

3. The two methods commonly used in iterators are:

    boolean Hasnext (): Determines if there is a next element;

    Boolean next (); take out the next element.

two ways to use 3.2 iterators
1  //Iterator Usage 12 for  (Iterator iter = Iterator (); Iter.hasnext ();) {3      System.out.println (Iter.next ()); 4  } 5   6  //iterator Usage 27  Iterator iter = L.iterator (); 8 while  (Iter.hasnext ()) {9      System.out.println ( Iter.next ());  
3.3 Enhanced for loop: A simplified method for iterators
1     // For (data type iteration variable name: Collection Object) 2      for (Object obj:c) {3         // Do something with obj 4     }

3.4 How do I add a collection element using iterators?

The iterator interface does not have methods to add elements, but its subinterfaces listiterator, so: With Listiterator iterations, iterators add elements. (The collection itself iterates, using the collection itself method to add elements, such as the add

four. List Interface4.1 List interface Method

Unique methods

    • void Add (int index,object Element): Inserts the specified element at the specified position in the list (optional action).
    • Object get (int index): Returns the element at the specified position in the list.
    • Object set (int index,object element): Replaces the element in the specified position in the list with the specified element (optional action).

implementation class for the 4.2 list interface
    • ArrayList: Thread is unsafe, query speed block, the bottom is using an array, adding and deleting slowly;
    • LinkedList: Thread insecure, linked list structure, adding and deleting fast, query slow;
    • Vector: Thread safe, but slow, has been replaced by ArrayList
4.3 List interface traversal method

1. Iterator traversal

1 // iterator Traversal list 2 Iterator it = list.iterator (); 3  while (It.hasnext ()) {4     Object obj = it.next (); 5     System.out.println (obj); 6 }

2. Enhanced for Loop

1 // enhanced for loop traversal collection 2  for (Object obj:list) {3    System.out.println (obj); 4 }

3. Normal for loop mate get method

1 // normal for loop, gets the element at the specified position 2  for (int i = 0;i<list.size (); i++) {3    System.out.println (List.get (i)); 4 }

4.4 Concurrency Modification Exceptions

When using iterators to traverse ArrayList, if the collection is modified using the method of the collection itself, it will result in concurrent modification exceptions: Concurrentmodificationexception, so be aware that:

    • Use iterator traversal to delete elements using iterators
    • Use the collection itself to traverse, delete elements using the collection itself method

Vector class

The vector class is already 1.0, and in 1.2 is integrated into the set framework, most of which are the same as ArrayList, but it is thread-safe, so inefficient, unique method:

    • void AddElement (E obj): Adds the specified component to the end of this vector, increasing its size by 1.
    • void Removeelement (): Removes all components from this vector and sets their size to zero.
    • Elements (): Returns an enumeration of the components of this vector.

LinkedList class

The LinkedList class uses the linked list structure to save data, most of the methods are the same as ArrayList, but there are several ways to manipulate the end-to-end elements.

    • void AddFirst (e E): Inserts the specified element at the beginning of this list.
    • void AddLast (E E): Adds the specified element to the end of this list.
    • E remove (): Gets and removes the header of this list (the first element).

The LinkedList bottom uses a linked list, but maintains an index, so it provides a way to get an element by index, but this method is inefficient and generally does not use

Summary: Implementation class selection for the list interface

Whether thread safety is required: if so, vectors can be selected, but other two kinds can be thread-safe in other ways, so vectors are not generally used;

If not, consider whether to delete more or more query, and delete more: use LinkedList; query multiple: Use ArrayList

Java Foundation (17), Collection Class (1:collection)

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.