1

Is it possible to parameterize an ArrayList from a method parameter? For instance, I have a method getAllViewsFromRoot(View root) which retrieves all Views from a layout. Now I want a method that gets all ProgressBars in a layout, so I can just use this (toolkit)method:

public static ArrayList<ProgressBar> getAllProgressBars(View root) {
  ArrayList<View> allviews = getAllViewsFromRoot(root);
  ArrayList<ProgressBar> results = new ArrayList<ProgressBar>();
  for (View view : allviews)
    if (view instanceof ProgressBar)
      results.add((ProgressBar)view);
  return results;
}

But since I need to do this for different kinds of Views, I wondered if this is possible in a more generic way, passing on the class in the method. I hoped this would work, but it doesn't:

public static ArrayList<?> getViewsFromViewGroup(ViewGroup root, Class clazz) {
    ArrayList<View> views = getAllViewsFromRoots(root);
    ArrayList<View> result = new ArrayList<clazz>();
    for (View view : views) {
        if (clazz.isInstance(view.getClass())) {
            result.add(view);
        }
    }
    return result;
}

And somewhere else I would call ArrayList<ProgressBar> pbs = Toolkit.getViewsFromViewGroup(root, ProgressBar.class).

In other words, can I specify how I want to strong type the ArrayList with a method parameter?

Is any sort of what I want possible? I don't necessarily need it badly, but I like to solve problems in a generic way.

EDIT

I've managed to get the code working with the answer below (Thanks to thkala). It's actually way easier that I suspected.

public static <T> ArrayList<T> getViewsFromViewGroup(View root, Class<T> clazz) {
    ArrayList<T> result = new ArrayList<T>();
    for (View view : getAllViewsFromRoots(root)) 
        if (clazz.isInstance(view)) 
            result.add(clazz.cast(view));
    return result;
}

So if you want to retrieve all ProgressBars from a certain point in your layout, just call:

ArrayList<ProgressBar> myPbs = Toolkit.getViewFromViewGroup(myRootView, ProgressBar.class);

1 Answer 1

3

How about this:

public static <T> ArrayList<T> getViewsFromViewGroup(ViewGroup root, Class<T> clazz) {
    ...
}

Class is a parametric type, so you can use its parameter to specify a generic parameter in a method. Naturally, you will have to use the T parameter in the method body - unless you plan on using reflection you could even completely ignore the clazz argument.

Sign up to request clarification or add additional context in comments.

1 Comment

@ChristiaandeJong But remember, that 'T' is not reifiable type, so you can't use it in Runtime. I mean that you can't do things like this: T t = new T();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.