Java Collection Class summary two

Source: Internet
Author: User
Tags map class

The previous chapter has summed up some of the basic characteristics of common set classes and their differences, the following, and then summarize the collection class part

First, the common method of collection class

1, Remove method: Remove the element operation, the following ArrayList as an example.

Import java.util.*;p ublic class demo_jihelei2{//definition test method public void Test_1 () {//remove () method test, one ArrayList for example list lis = new ArrayList (); Lis.add ("a"), Lis.add ("B"); Lis.remove (1);//remove Element Lis.remove ("B") based on index;//Remove from element}}

In general, the Remove parameter can be an index and a specific element, and there may be two parameters, the other way to see the API documentation, here is not cumbersome to introduce.

2. Traversal method

A, first, for the most commonly used list, the method of traversal mainly has three kinds, one ArrayList for example

for () loop traversal, this method is the same as the normal array traversal method.

for (int i = 0;i<lis.size (); i++) {System.out.println (Lis.get (i));}

For each method, see the code for specific usage

list<string> lis = new array<string> (); Note that you need to define the collection class as generic when using the for each traversal, and the knowledge of the generics will be summarized below. for (String A:lis) {System.out.println (a);} Of course, if you do not define the collection class as generic, you can also call ToArray () to get an object array of the current collection class objects and then use the for each to traverse the

  

In addition, for a collection class, one of the most common methods is to iterate through an iterator, see the following code to understand:

Use iterators to traverse iterator it = lis.iterator ();//iterators have corresponding methods that can be used to iterate over the end of the cursor (Hasnext ()) and get the corresponding element (next ()) while (It.hasnext ()) { System.out.println (It.next ());} while (It.hasnext ()) {System.out.println (It.next ());}

The same is true for vector traversal methods that also have cursors.

b, because the subclass of the set does not have a corresponding cursor, only the iterator can get the corresponding order of the elements in the collection, and then traverse, note that the result of each iteration is not necessarily, because each iterator gets the permutation of the elements is random, which also shows that the elements under the set is not sequential, please look at the code:

public void TreeSet () {HashSet hs = new HashSet () Hs.add ("a"); Hs.add ("B"); Hs.add ("B"); Hs.add (null); System.out.println (Hs.size ());//traversal mode iterator it = Hs.iterator (); while (It.hasnext ()) {System.out.println (It.next ()) (//) The output value is not necessarily the same at each time because the object in the implementation class under set is unordered;

D, for the common one of the following HashMap traversal method is also an iterator, which has two methods of traversal, one is to pass through the key, and then call the corresponding method to obtain the value of the corresponding element, the other way is through the entry ratio traversal.

1, method one uses the iterator through the key traversal iterator it1 = Mh1.keyset (). iterator (); int i = 0;while (It1.hasnext ()) {i++; System.out.println ("key" + i + "=" + It1.next ());//The Traversal order starts at the end? HashMap stored things are no order! }//2, method two uses iterators to traverse iterator it2 = Mh1.entryset () through Entry. iterator (); while (It2.hasnext ()) {Map.entry Entry = (map.entry) It2.next (); System.out.println (Entry.getkey () + ":" + entry.getvalue ()); /* Summary: For iterator, what kind of iterator method is used to construct it, the object that the next method returns is the type of object that constructs it */

Ii. Summary of generic types

1, what is generic, please first look at the example:

Import java.util.*;p ublic class demo_fanxing{public void test_fanxing () {//generics are defined as follows, ArrayList for example list<string> Lis = new arraylist<string> ();//A type parameter String is passed in <>, so the generic can actually be understood as a class Lis.add ("a") passed in when the parameter is initialized; Lis.add (new Integer (1));//error, the generic collection class can only add the same element, in this case only the string type}}

The above code shows that generics, in fact, is a class that is re-initialized when a type parameter is passed in. In a collection class, a generic collection class can only store the same type of element, as in the case of an ordinary array, except that it can vary in length accordingly.

2. The benefits and necessity of using generics: In the collection class, the use of generics makes programming flexible, passing the type as a parameter, is not only the typical performance of Java polymorphism, but also greatly increases the security of the program. There are a number of areas to be aware of in the use of generics, and further learning is required.

The Equals and = = Numbers use considerations in the collection class.

1, equals and = = Difference and contact:

The first thing to know is that Java has no pointers, but there is a mechanism in Java that looks like a pointer: objects that refer to objects in memory, actually remind us to use memory thinking when thinking to think about the construction and operation of the program. The reference to each object is actually equivalent to the pointer in the C language.

In programming, many times we need to know whether different references point to the same object, when we can compare by the = = number, and the function of the original Equals method of object and = = is actually the same. However, in subclasses of object, many implementation classes overload the Equals method for richer functionality, first look at the following example:

public void Methotfirst_equals () {String test1 = "a"; String test2 = "a"; Boolean B1 = (TEST1==TEST2);//output is Trueboolean b2 = test1.equals (test2);// The output is trueSystem.out.println ("= =" compares the results of two references to the same object = "+ B1); System.out.println ("equals" compares the results of two references to the same object = "+ b2);}

Obviously, in a string object, equals and = = are not overloaded, and there is no obvious difference between using the two. However, take a look at the following example:

public void Methot1 () {Integer test1 = new Integer (1), Integer test2 = new Integer (1), Boolean B1 = (TEST1==TEST2);//output is FAL Seboolean b2 = test1.equals (test2);//The output is trueSystem.out.println ("= = compares the results of two references to the same object =" + B1); System.out.println ("equals" compares the results of two references to the same object = "+ b2);}

By comparing the two examples above, we can find that: = = = Two references with a true result must point to the same object, that is, = = can compare two pairs of references to the same object; equals sometimes is the same as = = function, but more often, It allows for richer comparisons: for example, in an integer class, it can compare whether the internal data of two integer objects is the same, rather than whether it is the same object.

2. After understanding the difference between = = and equals, we will discuss the problem of how to use the two in the collection class.

First, take a look at the simple example:

 Public voidmethod2 () {List lis_1=NewArrayList (); Lis_1.add (A); Lis_1.add ("B"); List lis_2=NewArrayList (); Lis_2.add (A); Lis_2.add ("B"); BooleanB1 = (lis_1==lis_2);//The output is false because it is a different object and has a different position in memory        BooleanB2 = Lis_1.equals (lis_2);//The output is true because the Equals method of ArrayList has the ability to compare the internal data between objects for equalitySystem.out.println ("= = Comparison of different collection results with the same element =" +B1); System.out.println ("Equals compares different collection results with the same element =" +B2); }

Summary: The Equals method of the list implementation class overloads the method of object so that it can be called to compare elements inside the object, so it is a different object, as long as the inner element is the same, the result is true.

Let's look at the difference between the set implementation class equals and = = numbers.

public void Method4 () {Set hs_1 = new HashSet (); Hs_1.add ("a"); Hs_1.add ("B"); Set hs_2 = new HashSet (), Hs_2.add ("a"), Hs_2.add ("B"); Boolean B1 = (hs_1==hs_2);//output is Falseboolean b2 = hs_1.equals (hs_2 );//The output is trueSystem.out.println ("= = Compare the results of two HashSet objects with the same element" + B1); System.out.println ("Equals compares the results of two HashSet objects with the same element" + b2);}

It is found that the Equals method of the sub-class under the denomination and list below the set has the same function.

Summary: In all subclasses under collection, The Equals method compares the elements in the collection for equality and then results.

Finally, the collection classes in the map have different situations, see the following code:

public void Method5 () {Map hm_1 = new HashMap () hm_1.put ("1", "a"); Hm_1.put ("2", "B"); Map hm_2 = new HashMap () hm_2.put ("1", "a"), Hm_2.put ("2", "B"), Boolean B1 = (hm_1==hm_2),//output is Falseboolean b2 = hm_1. Equals (hm_2);//output is trueSystem.out.println ("= = compare two results of HashMap objects with the same element" + B1); System.out.println ("Equals compares the results of two HashMap objects with the same element" + b2);}

The above results show that when the different objects in the HashMap correspond to the same key value and value, the return is true, which is very well understood, but what will happen to the two objects of different key values, such as value, or key value? Take a look at the following code

The same key value, the execution of equals under different value is public void Method6 () {Map hm_1 = new HashMap (); Hm_1.put ("1", "a"); Hm_1.put ("2", "B"); Map hm_2 = new HashMap ();//the same key value, different value values Hm_2.put ("1", "C"), Hm_2.put ("2", "D"); Boolean B1 = (hm_1==hm_2);// The output is Falseboolean b2 = hm_1.equals (hm_2);//output is falseSystem.out.println ("= = compare two results of HashMap objects with different value values of the same key value" + B1) ; System.out.println ("equals" compares two results of a HashMap object with the same key value with different value values "+ b2);} Different key values, the execution of equals in the same value under public void Method7 () {Map hm_1 = new HashMap (), Hm_1.put ("1", "a"), Hm_1.put ("2", "B"); Map hm_2 = new HashMap ();//the same key value, different value values Hm_2.put ("0", "a"), Hm_2.put ("1", "B"); Boolean B1 = (hm_1==hm_2);// The output is Falseboolean b2 = hm_1.equals (hm_2);//output is falseSystem.out.println ("= = compare two results of HashMap object with the same value value of the same key" + B1 ); System.out.println ("Equals compares two results of a HashMap object with a value equal to the same key value" + b2);

Obviously, the above code shows that as long as the key and value values in the Map class are not equal, the returned result is false, which indicates that when we inherit the map interface, we need to compare the value of the key and value equal when overloading the Equals method.

Java Collection Class summary two

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.