Java Core Technology Learning notes of the five--java collection __java

Source: Internet
Author: User
Tags java se

13. 1 set interface

13. 1. 1 separating the interface of the set from the implementation

As is often the case with modern data structure class libraries, the Java Collection Class library separates interfaces (interface) from implementations (impementation). First, look at the familiar data structure-how queues are separated.

The queue interface indicates that elements can be added at the end of the queue. Deletes an element in the header of the queue, and can find the number of elements in the queue. Queues should be used when objects need to be collected and checked for objects according to the "First-in first out" rule.

Queues usually have two implementations: one is using a loop array, the other is using a linked list.

Collection interfaces and iterators in the 13.1.2Java class library

In the Java class Library, the basic interface of the collection class is the collection interface. This interface has two basic methods:

Boolean Add (E Element)

Iterator<e> iterator ();

The Add method is used to add elements to the collection. Returns true if the add element does change the collection, otherwise it returns false.

The iterator method is used to return an object that implements the iterator interface. You can use this iterator object to sequentially access the elements in the collection.

1. Iterators

The iterator interface contains three methods:

boolean hasnext ();

E next ();

void Remove ();

By repeatedly calling the next method, you can individually access each element in the collection. But if the end of the collection is reached, the next method throws a nosuchelementexception. Therefore, you need to call the Haas next method before calling the next method. This method returns true if there are more than one element for the iterator object to access. If you want to see all the elements in the collection, request an iterator and call the next method repeatedly when the Hasnext method returns True. After Java SE 5.0 iterators can be replaced with the For Each loop. The compiler translates the For Each loop into a loop with an iterator.

The collection interface extends the iterator interface. As a result, you can use the For Each loop for any collection in the standard class library.

The order in which elements are accessed depends on the collection type. If you iterate over ArrayList, the iterator will start with index 0, each iteration with an index value plus 1. However, if you access the elements in HashSet, each element will appear in a random order. Although it is possible to determine all elements that can traverse the collection during the iteration, it is not possible to predict the order in which the elements are accessed. This is not a problem for calculations that sum or peer review of the number of elements in a condition that is unrelated to the order.

Note: Programmers will notice that the next and Hasnext methods of the iterator interface are the same as the Nextelement and hasMoreElements methods of the enumeration interface. The designer of the Java Standard Class Library can choose to use the enumeration interface. However, they did not like the interface's cumbersome method name, and introduced a new interface with a shorter method name.

Note: There is also a useful analogy here. Iterator.next and Inputstream.rea can be seen as equivalent. Reading a byte from the data stream automatically "consumes" this byte. The next call to read will consume and return the next byte entered. In the same way, you can read all the elements in the collection repeatedly by calling the next method.

2. Delete Element

The Remove method of the iterator interface deletes the element that was returned when the next method was last called. In most cases, it is practical to look at this element before deciding to delete an element. However, if you want to delete the element at the specified location, you still have to cross this element. For example, here's how to delete the first element in a collection of strings:

Iterator<string> it =list.iterator ();

It.next ();

It.remove ();

3. Generic Practical method

Because collection and iterator are generic interfaces, you can write practical ways to manipulate any collection type. For example, the following is a generic method that detects whether any collection contains a specified element:

Public static <E> boolean contains (collection<e> c,object obj) {

for (E element:c)

if (Element.equals (obj))

return true;

return false;

}

Common methods in collection interfaces:

Method Summary

Boolean

Add (e E)
Make sure that this collection contains the specified element (optional operation).

Boolean

AddAll (COLLECTION< extends e> c)
Adds all the elements in the specified collection to this collection (optional operation).

void

Clear ()
Remove all elements in this collection (optional operation).

Boolean

contains (Object o)
Returns True if this collection contains the specified element.

Boolean

Containsall (collection<?> c)
Returns True if this collection contains all the elements in the specified collection.

Boolean

equals (Object o)
Compares this collection to whether the specified object is equal.

Int

hashcode ()
Returns the hash code value for this collection.

Boolean

IsEmpty ()
Returns True if this collection contains no elements.

Iterator<e>

iterator ()
Returns an iterator that iterates over the elements on this collection.

Boolean

Remove (Object o)
Removes a single instance of the specified element from this collection, if present (optional operation).

Boolean

RemoveAll (collection<?> c)
Remove all elements in this collection that are also included in the specified collection (optional operation).

Boolean

Retainall (collection<?> c)
Retain only those elements in this collection that are also included in the specified collection (optional operation).

Int

size ()
Returns the number of elements in this collection.

Object[]

ToArray ()
Returns an array that contains all the elements in this collection.

<T> t[]

ToArray (t[] a)
Returns an array containing all the elements in this collection; the Run-time type of the array returns the same as the run-time type of the specified array

It would be annoying to provide so many routines for each class that implements the collection interface. To enable the implementation to implement this interface more easily, the Java class Library also provides a class abstractcollection that abstracts the base method size and iterator, but provides a routine approach here. At this point, a specific collection class can extend this abstract class. The iterator method is now provided by the concrete collection class, and the Contains method is provided by the Abstractcollection superclass. However, if subclasses have more efficient ways of implementing contains methods, they can also be provided by subclasses.

Collection Note in use: Several of these methods may cause a unsupportedoperationexception exception; an classcastexception exception is generated when an attempt is to add an incompatible object to a set of classes; collection does not have a get () method to take an element and can only traverse the element through iterator ().

13. 2 Concrete Sets

In the following table, other classes implement the collection interface in addition to the classes that end with map. And the class with the end of map implements the map interface.

collection type

Description

ArrayList

An index sequence that can grow and shrink dynamically

LinkedList

An ordered sequence that allows efficient insertion and deletion at any location

Arraydeque

A two-terminal queue implemented by cyclic array

HashSet

A unordered set without repeating elements

TreeSet

An ordered set

Enumset

A set containing the values of enumerated types

Linkedhashset

A set that remembers the order in which elements are inserted

Priorityqueue

A collection that allows efficient deletion of the smallest element

HashMap

A data structure that stores key/value associations

TreeMap

A mapping table with ordered sequence of key values

Enummap

A mapping table with key values that belong to the enumeration type

Linkedhashmap

A mapping table that remembers the order in which key/value items are added

Weakhashmap

A mapping table whose value is not available to be reclaimed by the garbage collector

Identityhashmap

A mapping table that compares key values with = = instead of equals

13. 2. 1 Linked List

Arrays and array lists have a major flaw. This means that removing an element from the middle of an array costs a lot because all elements in the array after the deleted element move to the front of the array. Inserting an element in the middle of an array is also true.

Although shrimp processing references are stored in contiguous storage locations, the list stores each object in a separate node. Each node also holds a reference to the next node in the sequence. In the Java programming language, all linked lists are actually two-way links-that is, each node also holds a reference to the predecessor node.

Removing an element from a list is a very easy operation: you need to update the node near the deleted element.

However, there is an important difference between a linked list and a generic collection. A linked list is an ordered set, and the location of each object is important. The Linkedlist.add method adds an object to the tail of the list. However, it is often necessary to add elements to the middle of the list. Because the iterator is a description of the position in the collection, the location-dependent Add method is responsible by the iterator.

It is only practical to use iterators to add elements to a naturally ordered set. For example, the set type, where the elements are completely unordered. Therefore, there is no Add method in the iterator interface. Instead, the Collection class library provides the Sub-interface Listiterator, which contains the Add method:

Public Interface Listiterator<e> extends iterator<e> {

void Add (e e);

... ...}

Unlike Collection.add, this method does not return a Boolean value, which assumes that adding operations always changes the list. In addition, the Listiterator interface has two methods that can be used to reverse traverse the linked list.

boolean hasprevious ();

E Previous ();

When you call the add operation with an iterator that has just been returned by the iterator method and points to the list header, the newly added element will program the new header of the table. When an iterator crosses the last element of a linked list (that is, Hasnext returns false), the added element will program the new footer of the listing. The Add method relies on the position of the iterator, and the Remove method relies on the state of the iterator.

Finally, it is necessary to note that the set method replaces the previous element returned by the call next or previous method with a new element.

It can be imagined that if an iterator modifies a collection, another iterator traverses it, and there is a certain confusion. If the iterator finds that its collection has been modified by another iterator, or is modified by the collection's veteran method, a concurrent modificationexception is thrown.

Implementation of Next method:

Public E Next () {

checkforcomodification ()//Check whether the collection changes

int i = cursor;

if (I >= size)

throw New Nosuchelementexception ();

object[] Elementdata = ArrayList. this. Elementdata;

if (I >= elementdata.length)

throw New Concurrentmodificationexception ();

cursor = i + 1;

return (E) Elementdata[lastret = i];

}

The list iterator interface also has a method that can tell the index of the current position. In fact, conceptually, because a Java iterator points to a position between two elements, you can produce two indexes at the same time: The Nextindex method returns an integer index of an element when the next method is called The Previousindex method returns an integer argument that returns the element the next time the previous method is called. Of course, this index is only 1 smaller than the index value returned by Nextindex. The efficiency of these two methods is quite high, because the iterator holds the count of the current position. Finally, if you have an integer index N,list.listiterator (n) returns an iterator that points to the front of the element with the index n. That is, calling next and calling List.get (n) produce the same element, but it is less efficient to get the iterator.

If there are only a few elements in the list, there is absolutely no need to worry about the cost of the Get method and the set method. But why is the limited use of linked lists? The only reason to use a linked list is to minimize the cost of inserting or deleting elements in the middle of the list. If there are only a few elements in the list, you can use ArrayList entirely.

Linked lists are not used with random access:

for (IntI = 0; I < List.size (); i++) {

List.ge (i);

}

Every time you look up an element, you start the search again from the head of the list. The LinkedList object does not do any caching location information at all.

13. 2. 2 Array List

The list interface is used to describe an ordered set, and the position of each element in the collection is important. There are two protocols for accessing elements: one is using iterators, the other is randomly accessing each element with get and set methods. The latter does not apply to linked lists, but arrays are useful. The Collection Class library provides a ArrayList class of all attributes, and this class also implements the list interface. ArrayList encapsulates a dynamically reassigned array of objects.

Note: For an experienced Java programmer, a vector class might be used when a dynamic array is needed. Why use ArrayList instead of vectors? The reason is simple: all methods of the vector class are synchronized. The same vector object can be accessed securely by two threads. However, if a vector is accessed by one thread, the code spends a lot of time synchronizing. This situation is still very common. The ArrayList method is not synchronized, so quarantine uses ArrayList instead of vectors when synchronization is not required.

13. 2. 3 Hash Set

Linked lists and arrays can arrange the order of elements according to People's Will. However, if you want to view a specified element and then forget its location, you need to access all the elements until you find it. If the collection contains many elements, it will consume a lot of time. There are several data structures that can quickly find elements if they are not in the order of the elements. The disadvantage is that you cannot control the order in which elements appear. They will organize the data in accordance with principles that are conducive to operational purposes.

13. 2. 4 Tree Sets

The TreeSet class is very similar to a hash set, but it is somewhat improved than a hash set. A tree set is an ordered collection. You can insert an element into the collection in any order. When the collection is traversed, each value is automatically rendered in the order in which it is sorted. Adding an element to the tree is slower than adding it to the hash table, but it is a lot more than adding the element to the correct location of the array or list.

13. 2. 6 queues and two-terminal queues

Queues can make it effective to add an element to the tail and remove an element from the head. A two-head queue, a two-terminal queue, allows people to effectively add or remove elements at the head and tail while adding elements to the queue is not supported.

13. 2. 8 Mapping Table

The mapping table is used to hold key/value pairs.

If a key is provided, the value can be found. The Java Class Library provides two common implementations for the mapping table: HashMap and TreeMap. All two classes implement the map interface.

The key must be unique. You cannot store two values on the same key. If the put method is called two times for the same key, the second value replaces the first value. The Put method actually returns the last value stored with this key parameter. The Remove method is used to remove the element corresponding to the given key from the mapping table. The size method returns the number of elements in the mapping table.

transitions between collections and arrays

Array à collection: arrays.aslist

Set à array: toArray

Related Article

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.