Pits and Solutions of java in Deleting list Set

  • 2021-12-12 08:35:24
  • OfStack

Directory on list collection when deleting the pit solution to the common operation of List collection 1. list, Gets and deletes element 2. Whether an element is included in list 3. Change the element value according to the index in list ( Replace) 4. View (judge) the index of an element in list 5. Judge according to the index position of the element 6. Regenerate a new list (intercept collection) 7. Compare all the elements in two list 8. Judge whether list is empty 9. Return Iterator collection object 10. Convert the collection to string 11. Convert the collection to array 12. Convert the collection type 13. Deduplicate

About the pits when list set is deleted

When deleting an ArrayList, what are the problems if you use the following methods?


import java.util.ArrayList;
import java.util.List;
 
public class DeleteList {
 public static void main(String[] args) {
  List<Integer> list = new ArrayList<Integer>();
  list.add(1);
  list.add(2);
  list.add(3);
  list.add(3);
  list.add(3);
  list.add(4);
  for(int i=0;i<list.size();i++){
   if (list.get(i)==3) {
    list.remove(i);
   }
  }
  System.out.println(list);
 } 
}

Results: [1, 2, 3, 4].

Analysis question: Why is there a 3 left behind? Because when list [2] is accessed, the satisfaction is equal to 3, so delete it. At this point, the element after 3 moves one bit to the left, that is, the second 3 goes to i=2, and then i=3, deleting the third 3, so that the second 3 will be missed.

Solution

1. Access list from back to front, from i=size-1 to i=0, which can avoid the above problems;

2. Use the iterator iterator.


Iterator it = list.iterator();
  while (it.hasNext()) {
   Integer p = (Integer) it.next();
   if(p==3){
    it.remove();
   }
  }
  System.out.println(list);

Results: [1, 2, 4]

The following is part of the iterator source code: When executing the remove method, assign the current position to the cursor cursor, and then carry out next, or get the element of the current position, that is, the element moved from the next position. This avoids missing elements. The key point is that when deleted, the current position is i, the cursor position is i+1, and the modified cursor position is i.


       public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
 
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
 
            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

Common operations on List collection

Note: The code in the content is related.

1. Add, get and delete elements in 1. list

Add by: .add(e)

Get it by: .get(index)

The deletion method is: .remove(index)

Delete by index; .remove(Object o)

Delete according to element content;


List<String> person=new ArrayList<>();
            person.add("jackie");   // The index is 0  //.add(e)
            person.add("peter");    // The index is 1
            person.add("annie");    // The index is 2
            person.add("martin");   // The index is 3
            person.add("marry");    // The index is 4             
            person.remove(3);   //.remove(index)
            person.remove("marry");     //.remove(Object o)
             
            String per="";
            per=person.get(1);
            System.out.println(per);    ////.get(index)
             
            for (int i = 0; i < person.size(); i++) {
                System.out.println(person.get(i));  //.get(index)
            }

2. Does list contain an element

Methods:. contains (ES90o); Returns true or false


List<String> fruits=new ArrayList<>();
            fruits.add(" Apple ");
            fruits.add(" Bananas ");
            fruits.add(" Peach ");
            //for Cyclic traversal list
            for (int i = 0; i < fruits.size(); i++) {
                System.out.println(fruits.get(i));
            }
            String appleString=" Apple ";
            //true or false
            System.out.println("fruits Do you include apples in: "+fruits.contains(appleString));
             
            if (fruits.contains(appleString)) {
                System.out.println(" I like eating apples ");
            }else {
                System.out.println(" I'm not happy ");
            }

3. Change (replace) element value according to index in 3. list

Note. set (index, element); And. add (index, element); The difference;


String a=" Bai Longma ", b=" Sand monk ", c="8 Precept ", d=" Tang's monk ", e=" Wukong ";
            List<String> people=new ArrayList<>();
            people.add(a);
            people.add(b);
            people.add(c);
            people.set(0, d);   //.set(index, element);     // Will d Tang's monk put list The index in is 0 Replace the location of the a Bai Longma 
            people.add(1, e);   //.add(index, element);     // Will e Wukong put it list The index in is 1 Location of , In the original position b Sand monk moves backward 1 Bit 
             
            // Enhance for Cyclic traversal list
            for(String str:people){
                System.out.println(str);
            }

4. Index of View (Judge) Elements in list

Note:. indexOf (); And lastIndexOf ();


List<String> names=new ArrayList<>();
            names.add(" Liu Bei ");    // The index is 0
            names.add(" Guan Yu ");    // The index is 1
            names.add(" Zhang Fei ");    // The index is 2
            names.add(" Liu Bei ");    // The index is 3
            names.add(" Zhang Fei ");    // The index is 4
            System.out.println(names.indexOf(" Liu Bei "));
            System.out.println(names.lastIndexOf(" Liu Bei "));
            System.out.println(names.indexOf(" Zhang Fei "));
            System.out.println(names.lastIndexOf(" Zhang Fei "));

5. Judgment based on element index position


if (names.indexOf(" Liu Bei ")==0) {
    System.out.println(" Liu Bei is here ");
}else if (names.lastIndexOf(" Liu Bei ")==3) {
    System.out.println(" Where is Liu Bei ");
}else {
    System.out.println(" Where is Liu Bei? ");
}

6. Regenerate a new list (intercepted set) using the index position in list

Methods:

.subList(fromIndex, toIndex)   

.size() This method obtains the sum of the number of elements in list


List<String> phone=new ArrayList<>();
            phone.add("3 Star ");    // The index is 0
            phone.add(" Apple ");    // The index is 1
            phone.add(" Hammer ");    // The index is 2
            phone.add(" Huawei ");    // The index is 3
            phone.add(" Millet ");    // The index is 4
            // Original list Perform traversal 
            for(String pho:phone){
                System.out.println(pho);
            }
            // Generate new list
            phone=phone.subList(1, 4);  //.subList(fromIndex, toIndex)      // Using index 1-4 Object regeneration of 1 A list But does not contain an index of 4 Elements of, 4-1=3
            for (int i = 0; i < phone.size(); i++) { // phone.size()  The method obtains list The sum of the number of elements in the 
                System.out.println(" New list The contained elements are "+phone.get(i));
            }

7. Compare all the elements in the two list

The equals method 1 of two equal objects is defined as true, but two hashcode equal objects are not defined as equal objects


//1.<br>if (person.equals(fruits)) {
    System.out.println(" Two list All elements in the are the same ");
}else {
    System.out.println(" Two list All elements in the 1 Sample ");
}
//2.       
if (person.hashCode()==fruits.hashCode()) {
    System.out.println(" We're the same ");
}else {
    System.out.println(" We don't 1 Sample ");
}

8. Determine if list is null

//Null returns true, non-null returns false


Iterator it = list.iterator();
  while (it.hasNext()) {
   Integer p = (Integer) it.next();
   if(p==3){
    it.remove();
   }
  }
  System.out.println(list);
0

9. Returns an Iterator collection object


Iterator it = list.iterator();
  while (it.hasNext()) {
   Integer p = (Integer) it.next();
   if(p==3){
    it.remove();
   }
  }
  System.out.println(list);
1

10. Convert a collection to a string


Iterator it = list.iterator();
  while (it.hasNext()) {
   Integer p = (Integer) it.next();
   if(p==3){
    it.remove();
   }
  }
  System.out.println(list);
2

11. Convert a collection to an array


System.out.println(" Convert a collection to an array :"+person.toArray());

12. Collection type conversion


Iterator it = list.iterator();
  while (it.hasNext()) {
   Integer p = (Integer) it.next();
   if(p==3){
    it.remove();
   }
  }
  System.out.println(list);
4

13. De-repetition


Iterator it = list.iterator();
  while (it.hasNext()) {
   Integer p = (Integer) it.next();
   if(p==3){
    it.remove();
   }
  }
  System.out.println(list);
5

Complete code attached:


Iterator it = list.iterator();
  while (it.hasNext()) {
   Integer p = (Integer) it.next();
   if(p==3){
    it.remove();
   }
  }
  System.out.println(list);
6

Related articles: