java - Why doesn't ArrayList.contains(Object.class) work for finding instances types? -


say have arraylist populated objects of different types...

arraylist<fruit> shelf = new arraylist<fruit>(); apple apple = new apple(); orange orange = new orange(); pear pear = new pear();  shelf.add(apple); shelf.add(orange); shelf.add(pear); 

i want find out if shelf contains orange object. i've tried

shelf.contains(orange.class) 

but doesn't return true. understanding contains makes use of equals method object comparison, i'm not sure why case.

i realise can iterate through arraylist , check type of objects individually, i'm curious why contains doesn't behave way expect to.

you correct, contains uses equals. however, instance of class not equal object of class, i.e. orange.class.equals(new orange()) false.

you need custom method check list containing instance of class.

public static <e> boolean containsinstance(list<e> list, class<? extends e> clazz) {     (e e : list) {         if (clazz.isinstance(e)) {             return true;         }     }     return false; } 

and here's java 8 version making use of stream api , lambdas:

public static <e> boolean containsinstance(list<e> list, class<? extends e> clazz) {     return list.stream().anymatch(e -> clazz.isinstance(e)); } 

Comments

Popular posts from this blog

user interface - Python attempting to create a simple gui, getting "AttributeError: 'MainMenu' object has no attribute 'intro_screen'" -

jquery - Common JavaScript snippet to share files on Google Drive, Dropbox, Box.net or SkyDrive -

Android Gson.fromJson error -