如何正确调用泛型类型参数的方法,并取消对原始类型成员"未经检查的调用"警告

时间:2016-11-03 05:48:09

标签: java android

我已经为我的列表为不同的适配器子类创建了一个基类,它有一个带有泛型类型的List字段。该类的代码如下:

public class ListBaseAdapter<T> extends BaseAdapter {
    private List<T> items;

    @Override
    public int getCount() {
        if (items==null)
            return 0;
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return null;
    }

    List getDataset() {
        return items;
    }

    public void setDataset(List<T> items) {
        this.items = items;
    }
}

此外,下面是它的不同子类的一些示例:

public class UserListAdapter extends ListBaseAdapter {...}
public class AddressListAdapter extends ListBaseAdapter {...}

在ListFragment中,根据显示的不同类型的列表声明并初始化ListBaseAdapter字段。

public class TheListFragment extends ListFragment {
    private ListBaseAdapter adapter;

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        ...
        switch(type) {
            case 1:
                adapter = new UserListAdapter();
                adapter.setDataset(users); // this line of code is getting the warning of "unchecked call to member of raw type"
                break;
            case 2:
                adapter = new AddressListAdapter();
                adapter.setDataset(addresses); // this line of code is getting the warning of "unchecked call to member of raw type"
                break;
        }
        setListAdapter(adapter);
    }
}

代码工作正常,我也知道通过将Type设置为ListBaseAdapter,如下面的示例将摆脱警告:

private ListBaseAdapter<Users> adapter;

但如果我这样做,我将不得不在ListFragment中准备多个适配器,每个适配器都有一个特定类型。

我想知道是否有办法摆脱警告(不使用Lint)但仍然只维护一个适配器字段或者我是否正确地采用这种编码方式?

1 个答案:

答案 0 :(得分:2)

对于您的示例案例,您还应该使用类型初始化它们,即:

public class UserListAdapter extends ListBaseAdapter<Users> {...}
public class AddressListAdapter extends ListBaseAdapter<Address> {...}

如果您只想保留一个参考但仍然能够传递特定类型,那么根据您提供的代码,我推荐的内容将是这样的:

public class TheListFragment extends ListFragment {
    // You really don't even need to keep a reference to this
    // since it can be retrieved with getListAdapter()
    private ListBaseAdapter<?> adapter;

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        ...
        switch(type) {
            case 1:
                UserListAdapter userAdapter = new UserListAdapter();
                userAdapter.setDataset(users);
                adapter = userAdapter;
                break;
            case 2:
                AddressListAdapter addressAdapter = new AddressListAdapter();
                addressAdapter.setDataset(addresses);
                adapter = addressAdapter;
                break;
        }

        setListAdapter(adapter);
    }
}

如果您不需要为适配器进行将来的数据分配,那就可以了。您的字段仅为ListBaseAdapter<?>类型,但您的局部变量属于特定类型,因此您可以直接使用它们,然后将它们分配给更弱类型的字段adapter