I have a ListView listing a custom object (let's say MyObject
).
I want to filter it dynamically through an EditText
so I had to implement a getFilter()
with a publishResults method:
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
MyObjectAdapter.this.setItems((List<MyObject>) results.values);
MyObjectAdapter.this.notifyDataSetChanged();
}
At this point, Eclipse complains: Type safety: Unchecked cast from Object to List<MyObject>
I am sure this cast will always be true, but Eclipse only suggests to add @SuppressWarnings("unchecked")
but I'm totally against SuppressWarnings
because it's only hiding the problem, not a solution...
I tried adding:
if(results.values instanceof List<MyObject>)
But Eclipse complains again, and this solves nothing...
Cannot perform instanceof check against parameterized type List<MyObject>. Use the form List<?>
I know the casting will always be correct, but which is the proper way to make the code to be sure results.values
is actually a List<MyObject>
?
Thanks in advance!
Try something like this :
You can perform the checking before passing it to
setItems()
.However, you need to change your
setItems()
method accordingly:If all you have to work from is an
Object
, then you can't check at runtime that you actually have aList<MyObject>
, because the generic typeMyObject
is only used for compile-time type checking, it is not available at runtime. This is why you get an error when you try to add theinstanceof
check.If you are sure that your
Object
really is always aList<MyObject>
then I'd say the@SuppressWarnings
is OK, if you document why you are sure it is not a problem.If you absolutely want to avoid a warning though, you could create your own
List
implementation (say,MyObjectList
) that is not itself generic but implementsList<MyObject>
. Then you can do aninstanceof
check againstMyObjectList
at runtime.Another option is to check for and cast to
List<?>
as theinstanceof
error suggests. Then you can iterate over the elements in the list and check if they are actually all instances of MyObject, and copy them to a newList<MyObject>
.Well, I finally managed to find a solution.
Just as @Medo42 said:
Even though I did not went through the process of creating a whole new object in order to make this particular case to work "warning-less" this was the right direction to go.
So I took @lokoko 's idea and use it in a new
setItems()
method, with anObject
parameter instead of aList<MyObject>
in order to make sureThe result code is the following:
Thanks everyone for your help!