Java Learning Note (Core Java) 9 generics

Source: Internet
Author: User
Tags iterable

Collection interface
First, Introduction:
interface and implementation separation, use queue example
Provide interface specification
Interface Queue
{...}
Specific implementation
Class linkedlistqueue<e> impements queue<e> {...}
Class circulararrayqueue<e> impements queue<e> {...}

queue<customer> e = new linkedlistqueue<customer>

Second, iterators
1. The basic interface of the collection class is collection, which consists of two basic methods:
public interface Collection
{
Boolean Add (E element);
Iterator<e> Iterator ();
...
}

public interface iterator<e>
{
E next ();
Boolean hasnext ();
void Remove ();
}
From Javase 5.0, you can use the for each method to loop the operation
For each can work with any object that implements the Iterable interface
public interface iterable<e>
{
Iterator<e> iterator ();
}

C + +: different from C + +. The C + + iterator pointer can be moved individually on the STL template.
for (Vector<int>::iterable it = Vect.begin (); It! = Vect.end (); it++) Gets the value of the object that the pointer refers to by dereferencing the pointer
But unlike Java, when Java traverses the entire collection, the next method must be called before the pointer moves down. Before each move, you need hasnext to determine if the next value exists. In a sense. Find the operation pointer is tightly connected when moving.

2. Deleting an element
The Remove method in the iterator interface removes the element when the last next method returns. Therefore, when you call the Remove method, you must first call the next method.
3. Practical methods for generics (example)
public static <E> Boolean contains (collection<e> C, Object obj)
{
for (E element:c)
if (element.equal (obj))
return true;
return false;
}
Many of the collection interface declarations are similar to the generic methods described above
Abstract classes that are easier to implement than collection
Public abstract class Abstractcollection<e> implements Collection<e>
{
Public abstract Iterator Iterator ();
public boolean contance (object obj)
{
for (E element:c)
if (element.equal (obj))
return true;
return false;
}
...
}
API Original Book 567 page

Iii. Specific Collection
ArrayList index Vector
LinkedList Efficient Insert Delete List
Arraydeque loop array double-ended queue
Hastset unordered collection with no repeating elements
TreeSet ordered Collection
Emnuset contains the set of enum types
Linkedhastset remember the collection of element insertion order
Priorityqueue allows efficient deletion of the minimum element collection
Hastmap Key-value pairs
TREEMAP-Ordered mapping table
Linkedhastmap remember the collection of key-value pairs in the insertion order
Weakhashmap Value Invalid mapping table that can be reclaimed by garbage collection period
Identityhaspmap a mapping table using = = rather than equals to compare key values

Set is a collection of elements without duplicates

1. Linked list:
A linked list is an ordered collection, so you can use the Add method to insert an element anywhere in the list. There is no such method for unordered collection Hastset
There are also two methods in the Listiterator interface for reverse traversal
E Previous (); Reverse traversal of elements
Boolean hasprevious ()

Remove always deletes the last element that next/previous just traversed
The Add method relies on the location of the iterator
The Remove method relies on the state of the iterator

The set method is used to replace the element that next/previous just traversed
Listiterator<string> iter = List.listiterator ();
String OldValue = Iter.next ();
Iter.set (NewValue);

Iterators point to two elements, so you can return two points to the object. Use the Nextindex method to return the integer index of the next element that will be traversed. Previous returns the integer index of the element just traversed

Get method, not high efficiency ...
Simple example:
List<string> a = new LinkedList ();
A.add ("HH")
Listiterator<string> iter = A.listiterator ();
while (Iter.hasnext ())
{
A.next ();
A.remove ();
}

API Original Book 575 page

C++:
List<string> list;
List<string>::iterator ITER;

List.push_back ("HH");

for (it = List.begin (); it! = List.end; it++)
{
Std::cout << *it << std::end;
}

2. Array list ArrayList
Same as list. However, the Set/get method is useful for lists with arrays as the underlying package

3. Hash set quickly find the desired object
Hash list computes an integer for each object, which becomes a hash code
A hash code is an integer generated by the actual field of the object
Objects with different data fields will produce different hash codes
(If you are customizing a domain, implement the Hashcode method.) The method to be implemented is the same as the equal method, that is, when A.equal (b) is true, A, b must have the same hash code) = = "Specific Fifth Chapter

The hash table is implemented using a linked list array. Each list is called a bucket. To find the position of an object in a table, calculate its hash code and then take the remainder of the bucket. Gets the index of the object element.

Set is a collection of elements that have no duplicates. The Contains method is redefined to quickly see if an element has been inserted. Add an element using the Add method. The order in which it is accessed is almost random.

API Original Book 578 page

4. Tree Set
TreeSet is very similar to a hash set, which is an ordered set of elements that can be inserted into a collection in any order. The duration will be accessed in turn.

Adding elements to treeset is slower than adding to the hash list, but it is much faster than adding elements to the correct location of a linked list or array. Also, TreeSet can be automatically sorted

TreeSet ();
TreeSet (collection<? extends e> elements);

5. Comparison of objects CompareTo methods and equal methods

6. Queue and double-ended queue (does not support adding elements in the middle of the queue)
JAVASE6 introduces the Deque interface and is implemented by the Arraydeque and LinkedList classes

Api:
If full, throw an exception iilegalstateexception
Boolean Add (E element);
If full, return false
Boolean offer (E element);

If it is not empty, the header element is deleted and returned, and if it is empty, an exception is thrown nosuchelementexception
E Remove ();
Ibid., null if NULL is returned
E poll ();

If not empty, the return header element is not deleted, and if empty, throws an exception nosuchelementexception
E element ();
Ibid., null if NULL is returned
E Peek ();

If full, throw an exception iilegalstateexception
void AddFirst (E element)
void AddLast (E element)
If full, return false
Boolean Offerfirst (E Element)
Boolean offerlast (E Element)

If it is not empty, the header element is deleted and returned, and if it is empty, an exception is thrown nosuchelementexception
E Removefirst ();
E Removelast ();
Ibid., null if NULL is returned
E Pollfirst ();
E Polllast ();

If it is not empty, the header element is deleted and returned, and if it is empty, an exception is thrown nosuchelementexception
E GetFirst ();
E GetLast ();
Ibid., null if NULL is returned
E Peekfirst ();
E Peeklast ();

Arraydeque ();
Arraydeque (int initialcapacity);
Initial capacity 16 or given initial capacity constructs an infinite double-ended queue

7. Priority queue
Elements can be entered in any order, but are always retrieved in sorted order. Whenever the Remove method is called, the smallest element in the current priority queue is always fetched, but the priority queue is not sorted.
Use data Structure = = "Heap
The heap is a self-adjusting two-fork tree. You can have the smallest elements move to the tree root without having to spend time sorting.

Typical case: Task scheduling
Priorityqueue ();

Constructs a priority queue for holding compareable objects
Priorityqueue (int initialcapacity);
Constructs a priority queue and sorts the elements with the specified comparer
Priorityqueue ();

8. Mapping table Key-value pairs--------------Dictionary
HASHMAP (hash map) and treemap (Tree mapping table), these two classes all implement the map interface
Hash mapping Table Hash key
The Tree mapping table is sorted by the key's overall order and consists of a search tree

Hash a little faster, if you don't need sequential access, it's best to choose hash

Put method new or change the value of the key
Remove (); the value corresponding to the DELETE key size ();//Returns the number of elements

Java Learning Note (Core Java) 9 generics

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.