how to check if a specific 'type of class' is in a list?

Hi all,

I had a similar problem as below but I managed to solve it with an interface. Out of curiosity I wonder how to solve this:

I'm trying to crate a utility class that checks if list contains an instance of a specific class.

I'm not sure what is the 2nd argument I should pass to the method.

example:

List list =new ArrayList();

list.add(new Integer(1));

list.add(new Integer(2));

list.add(new Double(15.35));

list.add("hello there");

.

.

//here, I would like to check if the list contains a String

boolean flag = Utilities.contains(List list, ?);

.

.

.

publicstaticboolean contains(List list, ?)//not sure what to put here (Class clazz?)

{

Iterator itr = list.iterator();

while (itr.hasNext())

{

Criteria c = (Criteria) itr.next();

if (cinstanceof clazz)

returntrue;

}

returnfalse;

}

[1654 byte] By [xianwinwina] at [2007-11-27 11:06:30]
# 1

Here's something I use to check that all instances in a collection implement a particular class/interface:

public static void checkAllInstanceOf( final Collection items,

final Class parentClass )

{

for ( final Iterator it = items.iterator(); it.hasNext(); ) {

final Object o = it.next();

if ( ! parentClass.isInstance( o ) ) {

final String parentName = parentClass.getName();

throw new IllegalArgumentException(

"All items in collection must have '" + parentName + "' as parent; " +

"offending object is of class '" + o.getClass().getName() + "'" );

}

}

}

You'd invoke it like:

boolean valid =

Util.checkAllInstanceOf( someCollection, SomeInterface.class );

cwinters@vocollect.coma at 2007-7-29 13:15:51 > top of Java-index,Java Essentials,Java Programming...
# 2

thanks, this can work

xianwinwina at 2007-7-29 13:15:51 > top of Java-index,Java Essentials,Java Programming...