The collection of the Java JDK7 Learning Note

Source: Internet
Author: User

I. Collection of objects using collection

1. Understanding the Collection architecture

Java SE provides an API to meet a variety of needs, before using these APIs, it is recommended to understand their inheritance and interface operation schema, to understand when to use which class, and how the class to work with each other, and not become a dead-back API or copying paradigm dilemma.

For the requirements of the collection object, Java SE provides the collection API with its interface inheritance schema:

The behavior of the collection object, like the Add () method of the new object, removes the object's remove () method, which is defined in java.util.Collection. Since the object can be collected, it is also possible to remove the object individually, which is the behavior defined by the java.util.Iterable, which defines the iterator () method to return the java.util.Iterator operand, allowing you to get the collected objects one at a--

The common behavior of the collection objects is defined in collection, but the collection objects have different requirements. If you want to record the index order of each object at collection time, and you can take the object out of index order, Such behavior is defined in the Java.util.List interface, and if you want to collect objects that do not duplicate, have the behavior of the collection, you can use the Java.util.Set interface definition, if you want to collect objects as a queue, the collected objects are added from the tail, and the objects are removed from the front end, you can use the Java.util . Queue interface definition; You can use Java.util.Deque if you want to join, remove, and so on both ends of a queue.

When objects are collected, different interfaces are used to manipulate objects depending on the requirements. If you want to collect the index order, one way is to use an array, and the array operation list is java.util.ArrayList.

The Java SE API not only provides a number of operational classes, but also takes into account the need for the user to expand the API itself to collect the basic behavior of the object. The java.util.abstractCollection provides the basic behavior of the collection, and Java.util.AbstractList operates the basic behavior of the list, and can inherit abstractcollection to operate its own coll if necessary. Ection, inheriting abstractlist to manipulate their list, is much easier than directly manipulating collection and list interfaces.

2. List with index

List is a kind of collection, the function is to collect objects, and keep the Order of collection objects by index, one of its operation classes is java.util.ArrayList, its operation principle is as following example:

public class guest{

public static void Main (string[] args) {

List List = new ArrayList (); <----using the list and ArrayList of Java SE

Scanner Scanner = new Scanner (system.in);

String name;

while (true) {

System.out.println ("Visitor Name:");

Name = Scanner.nextline ();

if (Name.equals ("Quit")) {

Break

}

List.add (name);

}

System.out.println ("Visitor list:");

foreach (list);

}

private static void foreach (List list) {

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

String guest = (string) list.get (i);

System.out.println (Guest.touppercase ()); <----use Get () to get collected objects by index

}

}

}

Looking at the API file, you can see that the list interface defines many methods for indexing operations, such as Add (), remove (), set (), and so on. The Java.util.LinkedList also operates a list interface.

· ArrayList characteristics

When using the java.util.ArrayList operation, it is internal to use an object array to hold the collected objects, and therefore considering whether to use ArrayList, it is equal to consider whether to use the attributes of the array.

Array in memory will be continuous linear space, according to the index random access speed, if the operation of such requirements, such as sorting, you can use ArrayList, can get better speed performance.

Arrays are contiguous linear spaces in memory, and poor performance if you need to adjust the index order. For example, if you add an object to the position of index 0 by using the Add () method with the specified index in the ArrayList that has collected 100 objects, the object that originally indexed 0 must be adjusted to index 1, and the object of index 1 must be adjusted to 2 .... Using ArrayList to do this kind of operation is inappropriate, very good memory and speed.

The fixed length of the array is also an issue to consider, when the ArrayList internal array length is insufficient, a new array is created, and the reference to the old array is assigned to the new array, which is also a time-consuming and memory-intensive operation. For this ArrayList there is a constructor that specifies the capacity (capacity), and if you know roughly the range of objects that will be collected, you can save the cost described above by establishing an internal array of sufficient length beforehand.

· LinkedList characteristics

LinkedList uses the link structure when manipulating the list interface. If you do not know the link, please refer to the example:

public class simplelinkedlist{

Prvate class node{

Node (Object obj) {

This.obj = obj;

}

Object obj;

Node Next;

}

Private Node first;

public void Add (Object obj) {

if (first = = null) {

First = new Node (obj);

}else {

Node last = first;

while (last.next! = null) {

last = Last.next;

}

Last.next = new Node (obj);

}

}

public int size () {

int count = 0;

Node last = Forst;

while (last.next! = null) {

last = Last.next;

Count + +;

}

return count;

}

Public Object get (int index) {

int size = size ();

if (index >= size) {

Throws New Indexoutofboundsexception (

String.Format ("Index:%d,size:%d", index,size);

}

int count = 0;

Node last = first;

while (last < index) {

last = Last.next;

Count + +;

}

return last.obj;

}

}

In Simplelinkedlist, a new object is used within the node wrapper, and each time the Add () object is added, a chain structure is formed. 9.4

So every time the Add () object is created, a new node is set up to hold the object, not to consume memory beforehand, and if size () is called, the object length can be obtained by referencing the next object and counting from the first object. If you want to call get () to specify the index to get the object, then from the first object, one at a to reference the next object and count, you can get the object of the specified index. When you want to specify an index random Access object, the link method uses the method of finding the next element starting from the first element, which is less efficient, and the sort is not suitable for use with the list of linked operations.

Each element of the link references the next element, which facilitates the adjustment of the index order.

The new object will create a node instance wrapper, and first (or next on the previous node) re-reference to the new node object, and the new node's next refers to the next node object. Therefore, if the collected objects often have changes in the index of the situation, perhaps consider the connection mode operation of the list will be better, like a client login or logoff at any time the client list, the use of lindedlist will have a better efficiency.

3, the content does not duplicate the set

The same is the collection of objects, in the collection process if there is the same object, it is not repeated collection, if there is such a requirement, you can use the set interface to manipulate the object. For example, if you have a string that has many English words, and you want to know that there are several words that are not duplicated, you can write the following procedure:

public class words{

public static void Main (string[] args) {

Scanner Scanner = new Scanner (system.in);

System.out.println ("Please enter English");

String line = Scanner.nextline ();

string[] tokens = Line.split ("");

Set words = new HashSet ();

for (String Token:tokens) {

Words.add (token);

}

System.out.printf ("Duplicate words have%d:%s%n", words.size (), words);

}

}

The Aplit () method of the string, which specifies how the string is to be cut, where split () will return string[], including each string that is cut, and each string in string[] is added to the set operation HashSet. Because the set's characteristics are not duplicated, so if there is the same word, it will not be repeated, and finally just call the set's size () method, you can know the number of strings collected, HashSet's ToString () operation, it will include the collected string.

The Set collection uses the object's Hashcode () and the Equals () method to determine whether the object is the same. Take HashSet as an example, open space in memory, each space will have a hash code (hash code),

These spaces become hash buckets (hash buckets), and if the object is to join HashSet, the object's Hashcode () is called to get the hash code, and an attempt is placed into the hash bucket of the corresponding number, and if there is no object in the hash, it is placed directly, 9.6, or if there is already an object in the hash bucket. The object's Equals () will be called again for comparison, as shown in 9.7.

If an object is already in the same hash bucket, the object that is called Equals () is compared with the object to be joined, or false to represent two objects that are distinct objects that can be collected, or true to indicate that two objects are duplicates and cannot be collected.

In fact, many of the Hashset,java are called Hashcode () and the Equals () method, so it is recommended in the specification that two methods must be manipulated simultaneously.

4. Queue that supports queued operations

If you want to collect objects that can be queued, the collected objects are added to the end, and the object can be obtained from the front end, then you can use the queue interface's operand.

The queue inherits from collection, so it also has the collection add (), remove (), Element () method, but the queue defines its own offer (), poll () and Peek (), the main difference is that A method such as add (), remove (), Element () throws an exception when the operation fails, and a specific value is returned when a method operation such as offer (), poll (), and Peek () fails.

If an object has an operation queue and is intended to be used in queues, and the queue length is limited, it is generally advisable to use methods such as offer (), poll () and Peek ().

The offer () method is used to join the object on the back end of the queue, returns true after success, and false if it fails. The poll () method is used to remove the queue front-end object and returns null if the queue is empty.

The peek () method is used to get (but not take out) the queue front-end object and returns null if the queue is empty.

The LinkedList interface, which not only operates the list interface, but also operates the queue behavior, so it can be used as a queue for LinkedList.

If you want to operate on the front and end of the queue, adding objects to the front end and fetching objects, adding objects at the end and fetching objects, the sub-interface of queue deque defines such behavior.

Methods such as AddFirst (), Removefirst (), AddLast (), Removelast (), getlast () are defined in deque, and exceptions are thrown when the operation fails. Methods such as Offerfirst (), Pollfirst (), Peekfirst (), Offerlast (), Polllast (), and Peeklast () will return a specific value if the operation fails.

The behavior of the queue is duplicated with the behavior of the deque, and there are several actions that are justified, as shown in table 9.1:

Java.util.ArrayDeque operates the Deque interface, the following example uses Arraydeque to manipulate a stack with limited capacity:

public class stack{

Private Deque Deque = new Arraydeque ();

private int capacity;

public Stack (int capacity) {

This.capacity = capacity;

}

Public boolean push (Object o) {

if (deque.size () +1 > capacity) {

return false;

}

return Deque.offerlast (o);

}

Public Object pop () {

return Deque.polllast ();

}

Public Object Peek () {

return Deque.peeklast ();

}

public int size () {

return Deque.size ();

}

public static void Main (string[] args) {

Stack stack = new stack (5);

Stack.push ("Justin");

Stack.push ("Monica");

Stack.push ("Irene");

System.out.println (Stack.pop ());

System.out.println (Stack.pop ());

System.out.println (Stack.pop ());

}

}

The stack structure is advanced, so you only have to show Justin at the end of the results.

5, access to the object of the iterator

Write a foreach () method that displays all objects collected by the list:

public static void foreach (List list) {

for (int i = 0; i < list.size (); i++) {

System.out.println (List.get (i));

}

}

This method applies to all objects that manipulate the list interface, such as ArrayList, LinkedList, and so on. There is a ToArray () method in the set interface to return the object collected by the set to object (). The next foreach () method displays the objects that the set collects:

public static void foreach (Set set) {

For (Object O:set.toarray ()) {

System.out.println (o);

}

}

This method applies to all objects that operate the set interface, such as HashSet, TreeSet, and so on.

Write a foreach () method to display all objects collected by the queue:

public static void foreach (Queue queue) {

while (Queue.peek ()! = null) {

System.out.println (Queue.poll ());

}

}

The Queue.poll () method in the above method is to take out the objects in the stack, and when all the objects in the queue are displayed, the queue is empty.

Both list, set, and queue have a iterator () method, which is defined in the collection interface before JDK1.4, and the list, set, and queue inherit from collection. So all have the iterator () behavior.

Iterator () The Java.util.Iterator method returns the operand of the interface, which includes all objects collected by collection, and can use Iterator's hasnext () to see if there is a next object, and if so, then use next () to get the next object. Therefore, whether it is list, Set, queue, or any collection, you can use the following foreach () to display all collected objects:

public static void foreach (Collection Collection) {

Iterator Iterator = Collection.iterator ();

while (Iterator.hasnext ()) {

System.out.println (Iterator.next);

}

}

After JDK5, the iterator (), originally defined in collection, is promoted to the new Java.util.Iterator parent interface, so after JDK5, all objects collected can be displayed using the following foreach () method:

Publlic static void foreach (Iterator Iterator) {

Iterator Iterator = Iterator.iterator ();

while (Iterator.hasnext ()) {

System.out.println (Iterator.next ());

}

}

There is an enhanced for loop after JDK5, in fact an enhanced for loop is essentially a iterator iterator. As in the following example:

public class foreach{

private static void foreach (Iterator Iterator) {

for (Object o:iterator) {

System.out.println (o);

}

}

public static void Main (string[] args) {

List List = Arrays.aslist ("AAA", "BBB", "CCC");

foreach (list);

foreach (New HashSet (list));

foreach (New Arraydeque (list));

}

}

The example above uses the Java.util.Arrays static method Aslist (), which accepts variable-length arguments and collects the specified arguments as a list. List is a iterator, you can use the foreach () method.

Enhanced for loop when using the iterator object, the underlying is compiled as:

private static void foreach (Iterator Iterator) {

Object o;

for (Iterator i$ = Iterator.iterator ();

I$.hasnext ();

System.out.println (o) {

o = I$.next ();

}

}

In fact, the enhanced for loop invokes the Iteartor () method, using the returned iterator object to iterate through all the collected objects.

6. Sort the collected objects

After collecting objects, the usual operation is to sort the collected objects, Java.util.Collections provides a sort () method. The sort () method accepts only the list operand because it must have an index to sort.

Example of sort numbers:

public class sort{

public static void Main (string[] args) {

List numbers = arrays.aslist (10,2,3,1,9,15,4);

Collections.sort (numbers);

SYSTEM.OUT.PRINTLN (numbers);

}

}

The Collections.sort () method is ordered in a positive order, from small to large.

· Operation comparable

The collections sort () method requires the ordered object, which must operate the Java.lang.Conparable interface, which has a CompareTo () method that must return a result greater than 0, equal to 0, or less than 0.

The collections sort () method takes a object (Cast) as a comparable (and therefore throws classcastexception if the object does not operate comparable) when a object is compared to the B object. Then call A.compareto (b), if the A object is smaller than the B object, you must return a value less than 0, or 0 if the order is equal, or a value greater than 0 if the sequence a object is greater than the B object.

· Operation Comparator

When the manipulated object cannot manipulate comparable, or cannot get the original code or modify the original code, it is necessary to use comparator for custom sorting.

The collections sort () method has another overloaded version that accepts the operands of the Java.util.Comparator interface, and if this version is used, the order is determined by the Compara () definition of comparator.

7. Using generics

Examples of using generics:

The collection of the Java JDK7 Learning Note

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.