2

I am writing a generic java-android function that will accept as one of it's parameters an ArrayList<Object>, so that I can use all over my application regardless of the type of the ArrayList elements.

This is my function:

public GenericDisplayAdapter(Activity activity, ArrayList<Object> arrData) {

    this.m_ArrData = arrData;
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

When I try to to pass my ArrayList<CustomObject> as a parameter to this function, I get the error "can't cast from ArrayList<CustomObject> to ArrayList<Object>",

        m_LVStructDamageHeader.setAdapter(new GenericDisplayAdapter(
            (Activity)this, (ArrayList<Object>)arrStructDamageHeaders));

What is the best approach to handle such a situation, Thanks


Consider also, that it may be appropriate to give the GenericDisplayAdapter class a type parameter. E.g.

class GenericDisplayAdapter<T> {
    private List<T> m_ArrData;

    public GenericDisplayAdapter(Activity activity, ArrayList<T> arrData) {
        ...
    }
}

So then other methods can take advantage of this type parameter, instead of dealing in Object, they can use T.

4

4 回答 4

4

Change your function from

public GenericDisplayAdapter(Activity activity, ArrayList<Object> arrData)

to

public GenericDisplayAdapter(Activity activity, ArrayList<?> arrData)

Then you will be able to pass ArrayList<T> for any T. ArrayList<?> is almost like ArrayList<Object>, but the difference is that while you can add ANY object into the ArrayList<Object> (which is pretty bad if you pass e.g. ArrayList<CustomObject> there), you cannot add anything into the ArrayList<?> (which is fine).

于 2012-04-10T07:10:39.103 回答
2

change the method parameter

ArrayList<Object> to ArrayList<? extends Object>
于 2012-04-10T07:10:05.047 回答
1

You should you generic ArrayList just like

public GenericDisplayAdapter(Activity activity, ArrayList<?> arrData) {

    this.m_ArrData = arrData;
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
于 2012-04-10T07:13:16.153 回答
1

还要考虑,给 GenericDisplayAdapter 类一个类型参数可能是合适的。例如

class GenericDisplayAdapter<T> {
    private List<T> m_ArrData;

    public GenericDisplayAdapter(Activity activity, ArrayList<T> arrData) {
        ...
    }
}

那么其他方法可以利用这个类型参数,而不是处理Object,可以使用T。

于 2012-04-10T07:06:22.477 回答