javaandroidunchecked-cast

Unchecked cast prblem


I have an auto complete adapter but i'm getting this warning: Unchecked cast: 'java.lang.Object' to 'java.util.ArrayList'

This is the code for my filter where i'm getting it:

private final Filter nameFilter = new Filter() {
    @Override
    public CharSequence convertResultToString(Object resultValue) {
        return ((UserNameAndPic) resultValue).getUserName();
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        if (constraint != null) {
            suggestions.clear();
            for (UserNameAndPic people : tempItems) {
                if (people.getUserName().toLowerCase().contains(constraint.toString().toLowerCase())) {
                    suggestions.add(people);
                }
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = suggestions;
            filterResults.count = suggestions.size();
            return filterResults;
        } else {
            return new FilterResults();
        }
    }

    @Override
    protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
        List<UserNameAndPic> filterList = (List<UserNameAndPic>) results.values;
        if (results.count > 0) {
            clear();
            for (UserNameAndPic people : filterList) {
                add(people);
                notifyDataSetChanged();
            }
        }
    }
};

it has a problem with the line:

List<UserNameAndPic> filterList = (ArrayList<UserNameAndPic>) results.values;

I know its just a warning and i can suppress it but I want to avoid the casting and not suppress the warning. Any one knows what to do?


Solution

  • The compiler doesn't know if the casting you're doing is correct and safe or not.

    If you can't avoid the casting (the best practice would be to avoid it, but you're not posting enough code to help) then you can just suppress the warning, like this:

    @SuppressWarnings("unchecked")
    

    You can do that at the method level, or even to the variable itself:

    @SuppressWarnings("unchecked")
    String v = (String) vToCast;
    

    I'm sure this question has been answered millions of times anyway...