Common methods for Java collection classes

Source: Internet
Author: User

The contains () method and the Remove () method in collection.

Boolean contains (Object O), which is used to determine whether an element is contained in the collection, if it contains, returns true, and does not contain a return of false. Combine the following code to see.

Import java.util.*;
PublicClasscollectiontest03{
PublicStaticvoidMainString[] (args) {
Collection c=NewArrayList ();
Integer i1=NewInteger (10);
C.Add (I1);True
System.Out.println (C.contains (I1));
Integer i2=NewInteger (10);
The contains () method is called by the Equals () method at the bottom of the
C.contains (I2);True
System.Out.println (C.contains (I1));

Manager m1=NewManager (100,"Zhang San");
C.Add (M1);
System.Out.println (C.contains (M1));True
Manager m2=NewManager (100,"Zhang San");
System.Out.println (C.contains (m2));False
}

/* Underlying source code
Public Boolean contains (Object i2) {
Return IndexOf (I2) >= 0; IndexOf (I2) >= 0; The result is true or false, which is return True (or false)
}
public int indexOf (Object i2) {
if (i2 = = null) {
I2 is compared to elements in ArrayList when the value is null
for (int i = 0; i < size; i++)
if (elementdata[i]==null)
return i; At this time i>=0
} else {
I2 compared to elements in ArrayList when no null value is available
for (int i = 0; i < size; i++)
if (O.equals (Elementdata[i]))
return i; I>=0
}
return-1;
}
*/
}
Class manager{
int No;
String name;
Manager (int no,string name) {
This.no=no;
This.name=name;
}
}

Post-run output:

true
true
true
false

In the above code,

1. Create the Collection object C, followed by integer i1=new Integer (Ten), new an integer type object, use C.add (i1), add I1 to set C, and finally use C.contains (I1); Determines whether the set C contains I1 and prints the result.

2.Integer i2=new Integer (10), new to an integer type Object I2, and I1 the same, System.out.println (C.contains (I2)), determines whether the set C contains i2 and prints the result, Note that there is no C.add () method in the first step, but the result is still output true. This is because the Equals () method is called at the bottom of the contains () method. Here we open the JDK's help document to see the underlying source code.

PublicBooleanContainsObject I2){
ReturnIndexOf (I2) >=0;IndexOf (I2) >= 0; The result is true or false, which is return True (or false)
}
PublicIntIndexOf (Object I2){
If(I2 = =NULL) {
I2 is compared to elements in ArrayList when the value is null
For(Inti =0; i < size; i++)
If(elementdata[i]==Null
ReturnI//At this time i>=0
   }&NBSP; else { &NBSP;
      // I2 is not NULL when compared to elements in ArrayList
        for  ( int i =&NBSP; 0; I < Size i++)
            if  (i2. Equals (Elementdata[i])
                return i;   &NBSP //i>=0
         }
    return&NBSP; -1;  
}

As can be seen from the underlying source code, the contains () method calls the IndexOf () method,

Public Boolean contains (Object i2) {

Return IndexOf (I2) >= 0;

}

IndexOf (I2) >= 0; I>=0, the result is true, otherwise false, which is return True (or false)

Next take a look at the indexof () method, i2 may be null or empty, and when i2 is null, compare elements in ArrayList with a for loop to traverse the elements in ArrayList, if Elementdata[i]==null, That is, when an element like I2 is found in ArrayList, the index in ArrayList is returned, and we know that the index is >=0, that is, the contains () method, return True. When i2 is not NULL, the For loop is still used to traverse elements in ArrayList (), and if I2 is found to be equal to an element in ArrayList, the index subscript of the element in ArrayList is returned, and contains ( ) method to return True. If neither of these conditions is satisfied, it means that the elements in the i2 and ArrayList are not equal, and the Return-1,contains () method return False.

3. Next we customize a manager's class, manager m1=new Manager (100, "Zhang San"), create an object M1,c.add (M1) of the manager type, add M1 to ArrayList, use contains ( ) method to determine whether the set C contains M1, then the manager m2=new Manager (100, "Zhang San"), new an object M2, added to the set C, using the contains () method to determine the output false, Because M1 and M2 are all new objects, their memory addresses are not the same, the manager class does not override the Equals () method, so the memory address is compared at the time of the judgment, and the return result is false.

4. If you want to compare content instead of memory addresses in the manager class, we can rewrite the Equals () method in Manager.

PublicBooleanequalsObject o) {
if (this = O) return true;
if (o instanceof Manager) {
Manager m = (manager) O;
if (m.no==this.no && m.name==this.name) {
return true;
}
}
return false;
}

It is important to note that the elements stored in the collection should override the Equals () method. System.out.println (C.contains (m2)) after overriding the Equals () method in Manager, printing the result to true.

Next look at the Remove () method.

Boolean remove (Object O); Delete an element in a collection

Look at the following code:

Import java.util.*;
PublicClasscollectiontest04{
PublicStaticvoidMainString[] (args) {
Collection c=NewArrayList ();
Integer i1=NewInteger (10);
C.Add (I1);
System.Out.println (C.size ());1
Integer i2=NewInteger (10);
C.Remove (I2);
System.Out.println (C.size ());0
Manager m1=NewManager (100,"Zhang San");
C.Add (M1);
Manager m2=NewManager (100,"Zhang San");
C.Remove (m2);
System.Out.println (C.size ());0
}
}
Classmanager{
IntNo
String name;
Manager (IntNo,string name) {
This.no=no;
This.name=name;
}
public boolean  equals ( Object o) {
  if  ( this == o) &NBSP; return&NBSP; true;
  &NBSP if  (o instanceof Manager) {
   manager m = ( Manager) O;
    if (m.no== this.no && m.name== this.name) {
      Return&NBSP; true;
   }
 }
    return&NBSP; false; &NBSP
 }
}

Understanding the knowledge points in the contains () method, the Remove () should easily be able to tell what the output is, and it is not explained in detail here. However, if the data is between [ -128~127], a "integer constant Pool" is introduced in Java, in the method area. The integer constant pool stores only data between -128~127. Integer i5=127; This program does not create objects in the heap, it is taken directly in the integer constant pool. This is the previous content, forgot to turn to the previous "Java packaging class" to review again.

Go deep into the Remove () method.

Import java.util.*;
Public&NBSP; class&NBSP; collectiontest05{
  public&NBSP; static&NBSP; void&NBSP; main ( string[] args) {
 collection c= new arraylist ();
 c. Add ( 1);
 c. Add ( 2);
 c. Add ( 3);
 iterator It=c.iterator ();
  while  (It.hasnext ()) {
   it.next ();
   it. remove ();   //remove element
  by the Remove () method of the iterator;
 system. Out.println (C.size ());   //0
 }
}

The above procedure is removed using the Remove () method of the iterator, when removed using the Remove () method of the collection, as follows:

Import java.util.*;
Public&NBSP; class&NBSP; collectiontest05{
  public&NBSP; static&NBSP; void&NBSP; main ( string[] args) {
 collection c= new arraylist ();
 c. Add ( 1);
 c. Add ( 2);
 c. Add ( 3);
 iterator It=c.iterator ();
  while  (It.hasnext ()) {
   object element= It.next ();
   c. remove (element); //Use the Remove () method of the collection
 }
 system.   Out.println (C.size ());
 }
} /span>

Compile pass, error after running:

Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
 at java.util.ArrayList$Itr.next(Unknown Source)
 at CollectionTest05.main(CollectionTest05.java:25)

This is because C.remove (element), when deleted using the Remove () method of the collection collection, means that after deleting an element, the collection has changed, and then the action of deleting the element must be re-fetched to the iterator of the set after the change, Otherwise, the report is abnormal after running. It is recommended that the remove () method of the iterator be used to delete the element.

Common methods for Java collection classes

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.