How to remove specific object from ArrayList in Java?

前端 未结 13 1629
旧时难觅i
旧时难觅i 2020-12-05 06:54

How can I remove specific object from ArrayList? Suppose I have a class as below:

import java.util.ArrayList;    
public class ArrayTest {
    int i;

    pu         


        
13条回答
  •  情深已故
    2020-12-05 07:50

    For removing the particular object from arrayList there are two ways. Call the function of arrayList.

    1. Removing on the basis of the object.
    arrayList.remove(object);
    

    This will remove your object but in most cases when arrayList contains the items of UserDefined DataTypes, this method does not give you the correct result. It works fine only for Primitive DataTypes. Because user want to remove the item on the basis of object field value and that can not be compared by remove function automatically.

    1. Removing on the basis of specified index position of arrayList. The best way to remove any item or object from arrayList. First, find the index of the item which you want to remove. Then call this arrayList method, this method removes the item on index basis. And it will give the correct result.
    arrayList.remove(index);  
    

提交回复
热议问题