The following example shows how to use the contains () method to find the specified element in the array:
Example 1
Import java. util. ArrayList;
Public class Main {
Public static void main (String [] args ){
ArrayList objArray = new ArrayList ();
ArrayList objArray2 = new ArrayList ();
ObjArray2.add (0, "common1 ");
ObjArray2.add (1, "common2 ");
ObjArray2.add (2, "notcommon ");
ObjArray2.add (3, "notcommon1 ");
ObjArray. add (0, "common1 ");
ObjArray. add (1, "common2 ");
System. out. println ("array element of objArray:" + objArray );
System. out. println ("array element of objArray2:" + objArray2 );
System. out. println ("does objArray contain the string common2? :"
+ ObjArray. contains ("common1 "));
System. out. println ("does objArray2 contain arrays? :"
+ ObjArray2.contains (objArray ));
}
}
The output result of the above code is:
Array elements of objArray: [common1, common2]
Array elements of objArray2: [common1, common2, notcommon, notcommon1]
Does objArray contain the string common2? : True
Does objArray2 contain arrays objArray? : False
For example, the While loop auto-increment operation traverses the array.
Java uses the While loop auto-increment operation to traverse the array instance. Java traverses array instances:
Public class BirdArray {
Public static void main (String args []) {
String [] str = new String [] {"sparrow", "e", "White Pigeon", "yellow Sparrow", "lark", "Peacock", "parrot ", "Danding crane "};
Int index = 0; // create an index variable
System. out. println ("There are many birds in the park, including :");
While (index <str. length) {// traverses the array
System. out. println (str [index ++]); // auto-increment index value
}
}
}
Result output:
Run:
There are many birds in the park, including:
Sparrow
E
Pigeon
Huang Que
Lark
Peacock
Parrot
Danding Crane
Build successful (total time: 0 seconds)
Creates an index variable index to specify the subscript of an array. As the index increases, the while loop will gradually traverse each element and output it to the console. Note the difference between ++ index and index ++.
++ Index: the index value is incremented, and then the incremental value is used.
Index ++: first use the index value, and then increase the value of the variable.