Reputation: 72
I have class A and two classes B and C which extend A. I have an array list which contains multiple instances of all of these classes. Can I have a method which takes in an object and returns all objects in the array list which is of the same type as the one given to the method and how would I go about doing this?
Upvotes: 0
Views: 700
Reputation: 2105
Assuming you have that object somewhere to point to your list List<A> yourOriginalList
If you are using Java 8 you can write a reusable filter method not just for B or C elements but for anything you want to compare. This is using the new lamba expressions introduced in Java 8.
public List<A> getFilteredList(Predicate<A> predicate){
List<A> filteredList = new ArrayList<A>();
for(A value : yourOriginalList){
if(predicate.test(value)){
filteredList.add(value);
}
}
return filteredList;
}
To filter for B objects, use :
List<A> filteredListOfB = getFilteredList((value) -> value instanceof B);
To filter for C objects, use :
List<A> filteredListOfC = getFilteredList((value) -> value instanceof C);
As you can seee you can write anything you want to test in the parameter of getFilteredList
(not tested for syntax error, but the idea is here)
Upvotes: 0
Reputation: 54639
Although it's already answered, I had started creating an example, as an MCVE, so I'll just drop this here:
import java.util.ArrayList;
import java.util.List;
public class TypeFilterTest
{
public static void main(String[] args) {
List<Object> list = new ArrayList<Object>();
list.add(1);
list.add(2.0f);
list.add(3.0);
list.add(4);
list.add(5.0f);
list.add(6.0);
list.add("seven");
list.add(null);
System.out.println("Integers : "+findSameType(list, Integer.class));
System.out.println("Floats : "+findSameType(list, Float.class));
System.out.println("Doubles : "+findSameType(list, Double.class));
System.out.println("Comparables : "+findSubType(list, Comparable.class));
}
private static <T> List<T> findSameType(List<? super T> list, Class<T> type)
{
List<T> result = new ArrayList<T>();
for (int i=0; i<list.size(); i++)
{
Object element = list.get(i);
if (element != null && element.getClass().equals(type))
{
result.add(type.cast(element));
}
}
return result;
}
private static <T> List<T> findSubType(List<? super T> list, Class<T> type)
{
List<T> result = new ArrayList<T>();
for (int i=0; i<list.size(); i++)
{
Object element = list.get(i);
if (type.isInstance(element))
{
result.add(type.cast(element));
}
}
return result;
}
}
Upvotes: 0
Reputation: 1500235
Sure - you'd use getClass()
to find the execution-time type:
private final List<A> allKnownValues = ...;
List<A> getAllValuesOfTheSameType(A sample) {
ArrayList<A> results = new ArrayList<>();
for (A candidate : allKnownValues) {
if (candidate.getClass() == sample.getClass()) {
results.add(candidate);
}
}
return results;
}
If you want to include subtypes, you could use:
if (sample.getClass().isInstance(candidate))
Upvotes: 2