#1. Array converted into ArrayList
To convert an array to ArrayList, programmers often do this:
list<string> list = Arrays.aslist (arr);
Arrays.aslist () returns ArrayList, but this class is a private static class under the array package, and this class is not java.util.ArrayList. The Java.util.Arrays.ArrayList class has a set (), a Get (), A contains () method, but there is no way to add elements to the list, so the size of the list returned by the call to this method is fixed. To create a real ArrayList, you should do this:
arraylist<string> ArrayList = new Arraylist<string> (Arrays.aslist (arr));
After such processing, the constructor parameter of the ArrayList can accept the collection type.
#2. Determine whether an array contains a value
Would normally do that
set<string> set = new Hashset<string> (Arrays.aslist (arr));
Return Set.contains (Targetvalue);
Such code can be run and can achieve the desired effect, but there is no need to convert a list to set, conversion to set often takes more time, can be optimized as follows:
Arrays.aslist (arr). Contains (Targetvalue);
Or it could be.
for (String S:arr) {
if (s.equals (Targetvalue)) return
true;
}
return false;
The first way is more readable than the second.
#2. Loop list, delete an element
Think about the output of the following code
arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D"));
for (int i = 0; i < list.size (); i++) {
list.remove (i);
}
SYSTEM.OUT.PRINTLN (list);
The output results are:
[B, D]
There is a very serious problem with this method, when an element is deleted, the size of the list becomes smaller and the index of the list changes, so when you delete multiple elements in a loop that iterates through the list, the result of the run is what you want.
You might know that using an iterator is the right way to delete an element, and you know that the For loop traversal iterator traversal principle is the same, but in fact it's not the same, think about the result of this code:
arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D"));
for (String s:list) {
if (s.equals ("a"))
List.remove (s);
}
It will throw a concurrentmodificationexception. Abnormal
But if you change the code like this, it's OK.
arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D"));
Iterator<string> iter = List.iterator ();
while (Iter.hasnext ()) {
String s = iter.next ();
if (S.equals ("a")) {
iter.remove ();
}
}
The. Next () method must be called before. Remove (), in the For loop in the above code, the compiler will not call until the element is removed. Next (), which throws the Concurrentmodificationexception. can go to see the source code of Arraylist.iterator ().