Java_colletction applications: Converting from HashMap to array

Source: Internet
Author: User

First, understand some of the following knowledge points:

1, collection is the interface of HashMap and array

2, the elements in the HashMap is not the order, and array is some

3, the HashMap into the array object, the elements in the order and the iterator traversal of the original HashMap in the same order.

4. The newly created array object corresponds to the list object in the parameter list; collection corresponds to the original HashMap (that is, the modification of an object automatically causes another object to change)

Let's talk about how to convert a HashMap object to an Array object

First, convert HashMap into collection objects

Through: Values () method

Why you can do this:

Notice that there is a member variable in the HashMap class:

transient volatile collection<v> values = null;

Notice the HashMap class, which has a member function:

Public collection<v> values () {
Collection<v> vs = values;
return (vs!= null vs: Values = new values ());
}

The value of the HashMap object is exactly what is returned.

Speaking of which, you should be aware that you are now holding only a collection object, is a step away from our goal.

To make a collection object an array object, we use the following methods:

<T> t[] ToArray (t[] a);

For this method, we need to explain. and give some examples to verify my understanding.

First, you can look at the source of the collection interface about <T> t[] ToArray (t[] a); Wushu:

(English can also students suggest directly to see the original introduction, because my English proficiency is limited, may not translate too ideal.) Afraid of fraught ah. )

/**
* Returns An array containing all of the elements in this collection;
* The runtime type of the returned array is the specified array.
* If the collection fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of the
* Specified array and the size of this collection.
*
* <p>if This collection fits on specified array with room to spare
* (i.e., the array has more elements than this collection), the element
* In the array immediately following the "end of" the collection is set to
* &LT;TT&GT;NULL&LT;/TT&GT;. (This is useful in determining the length of this
* Collection <i>only</i> If the caller knows that this collection does
* Not contain any <tt>null</tt> elements.)
*
* <p>if This collection makes the any guarantees as to what order its elements
* are returned by it iterator, this is must return to the elements in
* the same order.
*
* <p>like the {@link #toArray ()} method, which is acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* Precise control over the runtime type of the output array, and may,
* Under certain circumstances, is used to save allocation costs.
*
* <p>suppose <tt>x</tt> is a collection known to contain only strings.
* The following code can be used to dump the collection into a newly
* Allocated array of &LT;TT&GT;STRING&LT;/TT&GT;:
*
* <pre>
* string[] y = X.toarray (new string[0]);</pre>
*
* <tt>toarray (new object[0]) </tt> is identical in function to
* <tt>toarray () </tt>.
*
* @param a The array into which the elements of this collection are to be
* stored, if it is a big enough; Otherwise, a new array of the same
* Runtime type is allocated to this purpose.
* @return An array containing all of the "elements in" collection
* @throws arraystoreexception if the runtime type of the specified array
* is isn't a supertype of the runtime type of every element in
* This collection
* @throws NullPointerException If the specified array is null
*/

The above introduction is probably this meaning:

This method can return a new queue object that contains all the elements in the collection object that called the method, and the type of the element in this new queue object is based on the element type of the queue object in the argument list. If the original collection object has no more elements than the number of elements in the queue object in the argument list, a new list object is not created, and all the elements in the collection object are placed in the queue object in the argument list. Otherwise, you first create an element type that is the same as the queue object in the argument list, and the number of elements is in line with the original collection element, and then assigned. In addition, if the number of queue object elements in the argument list exceeds the original collection, the system fills the remaining positions with null elements.

In addition, the order of the elements in the new array object is the same as the order in which the elements in the original collection object are traversed using a iterator.

As with the ToArray () method, this method implements the conversion of the collection object to an array object. However, this method can more accurately control the element type of the new queue object than the ToArray () method, and can save memory in a particular case. Because when the queue object in the argument list is large enough, there is no need for additional application space to hold the new queue object, but to use the original space directly.

For example, X is a collection object that holds a string element. The following code shows how we can use a newly allocated queue object to hold a collection object:

string[] y = X.toarray (new string[0]);

Attention:

ToArray (new object[0]) is the same as ToArray ().

*

* @ parameter a specifies the element type of the newly transformed queue object through the element type of the queue object A. If the element of queue object A is not less than the number of elements of the collection object to be transformed, no additional memory space is required, and the elements of the original collection object are placed directly into queue object A.

* @ Returns a queue object that holds all elements of the original collection object

* @throws arraystoreexception element type conflict

* @throws The queue object in the NullPointerException argument list is empty

Experiment 1:

Purpose: To verify the number of elements in the queue object in the argument list, and how to save the new queue object if the space is reallocated

SOURCE 1:

Hashmap<string, String>test=new hashmap<string, string> ();
Test.put ("A", "a ' s value");
Test.put ("B", "B ' value");
String []test1=new string[3];

String[] Test2=test.values (). ToArray (Test1);

System.out.println ("test1:");
System.out.println (test1.length);

for (String V:test1) {

System.out.println (v);

}
System.out.println ("test2:");
System.out.println (test2.length);
for (String v:test2) {

System.out.println (v);

}

Console

Test1:
3
B ' s value
A ' s value
Null
Test2:
3
B ' s value
A ' s value
Null

Analysis:

The comparison is visible: The queue object Test1 in the parameter list and the target queue object Test2 all point to the new queue object, that is, they have memory space that is not allocated separately. Because the queue object in the argument list test1 more elements than the original collection object, the null element is filled in later.


SOURCE 2:

Hashmap<string, String>test=new hashmap<string, string> ();
Test.put ("A", "a ' s value");
Test.put ("B", "B ' value");
String []test1=new string[1];

String[] Test2=test.values (). ToArray (Test1);

System.out.println ("test1:");
System.out.println (test1.length);

for (String V:test1) {

System.out.println (v);

}
System.out.println ("test2:");
System.out.println (test2.length);
for (String v:test2) {

System.out.println (v);

}

Console

Test1:
1
Null
Test2:
2
B ' s value
A ' s value

Analysis:

The comparison is visible: The queue object Test1 in the argument list does not get any elements, and test2 has. Visible, a new memory space has been allocated.


Experiment Two:

Objective: To find out the corresponding relationship between two queue objects and the corresponding relationship between the collection object and the original HashMap object, but the two sets of corresponding objects will not affect each other.

Source:

Hashmap<string, String>test=new hashmap<string, string> ();
Test.put ("A", "a ' s value");
Test.put ("B", "B ' value");
String []test1=new string[2];

Collection<string>variable=test.values ();

String[] Test2=variable.toarray (test1);

Variable.remove ("B ' s value");

System.out.println ("Colletction object:" +variable.tostring ());
System.out.println ("Hashmap object:" +test);

Test.values (). ToArray (Test1);
System.out.println ("test1:");
System.out.println (test1.length);

for (String V:test1) {

System.out.println (v);

}
System.out.println ("test2:");
System.out.println (test2.length);
for (String v:test2) {

System.out.println (v);

}
test2[0]= "Kaiwii modify!";
System.out.println ("test2:");
System.out.println (test2.length);
for (String v:test2) {

System.out.println (v);

}
System.out.println ("test1:");
System.out.println (test1.length);

for (String V:test1) {

System.out.println (v);

}
System.out.println (Test.tostring ());
SYSTEM.OUT.PRINTLN ("Whether test contain the modified value:" +test.containsvalue ("Kaiwii modify!"));

Console

Colletction object:[a ' s value]
Hashmap object:{a=a ' s value}
Test1:
2
B ' s value
A ' s value
Test2:
2
B ' s value
A ' s value
Test2:
2
Kaiwii modify!
A ' s value
Test1:
2
Kaiwii modify!
A ' s value
{a=a ' s value}
Whether test contain the modified Value:false


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.