-1

Suppose there are few classes all extending an abstract class abc :-

public class mno extends abc { ... }
public class pqr extends abc { ... }
public class xyz extends abc { ... }

there is a list of objects which contains object of these class.

List<abc> f =new ArrayList<abc>();
f.add(new mno());
f.add(new pqr());
f.add(new xyz());

Is there a way to check if list f contains an object of class xyz and remove it from the list.

I tried f.contains(xyz.class) or f.contains(new xyz()) but it returned flase

rcipher222
  • 369
  • 2
  • 4
  • 15

3 Answers3

4

If you use java 8 you can do it:

f.removeIf(xyz.class::isInstance);
Roma Khomyshyn
  • 1,112
  • 6
  • 9
1

You could use Java 8 Streams.

List<abc> newList = new ArrayList<>(f)
            .stream()
            .filter(xyz.class::isInstance)
            .collect(Collectors.toList());
alayor
  • 4,537
  • 6
  • 27
  • 47
0

You need to use instanceof operator to check that an object is of specific type as shown below:

 Iterator<abc> iterator = f.iterator();
    while(iterator.hasNext()) {
       if(iterator.next() instanceof xyz) {
           iterator.remove();
       }
   }

Also, the above code uses Iterator to safely remove the objects from the list.

Also, I strongly suggest you follow the Java naming conventions for class, variable, etc. as your example class names abc, xyz, etc. are very poor.

Vasu
  • 21,832
  • 11
  • 51
  • 67