类型安全:未选中从Object转换到列表<&MyObject的GT; [英] Type safety: Unchecked cast from Object to List<MyObject>

查看:267
本文介绍了类型安全:未选中从Object转换到列表<&MyObject的GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ListView列出了自定义对象(比方说为MyObject )。

I have a ListView listing a custom object (let's say MyObject).

我想通过的EditText ,所以我不得不实施用getFilter()与publishResults动态进行过滤方法:

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();
}

在这一点上,Eclipse的抱怨:键入安全:未选中从Object转换到列表&LT;&MyObject的GT;

我相信这会投永远是真实的,但是Eclipse只是建议增加 @燮pressWarnings(未登记),但我完全反对燮pressWarnings ,因为它只是隐藏的问题,而不是解决方案......

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...

我尝试添加:

if(results.values instanceof List<MyObject>)

但是Eclipse再次抱怨了,这解决不了任何问题...

But Eclipse complains again, and this solves nothing...

无法执行instanceof检查对参数化类型列表&LT; MyObject来取代。使用表单列表&LT;&GT;

我知道铸件永远是正确的,但它是使code,以确保 results.values​​ 实际上是一个<$ C的正确方法$ C>列表&LT;&MyObject的GT;

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> ?

在此先感谢!

推荐答案

好了,我终于找到一个解决方案。

Well, I finally managed to find a solution.

正如@ Medo42说:

Just as @Medo42 said:

另一种方法是检查并转换为List作为的instanceof
  错误提示。然后,你可以在列表中的元素进行迭代,并
  检查它们是否为MyObject实际上所有实例,并将其复制到
  一个新的列表。

Another option is to check for and cast to List as the instanceof 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 new List.

虽然我没有通过,以便使这种特殊情况下创造了一个全新的对象的工作的警告少,这是个正确的方向的过程去了。

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.

所以我把@lokoko的想法,并在新的 setItems使用()方法,用对象参数,而不是一个列表与LT;为MyObject&GT; ,以确保

So I took @lokoko 's idea and use it in a new setItems() method, with an Object parameter instead of a List<MyObject> in order to make sure

结果code是以下内容:

The result code is the following:

public void setItems(List<MyObject> var){
    this.list = var;
}

public void setItems(Object var){
    List<MyObject> result = new ArrayList<MyObject>();
    if (var instanceof List){
        for(int i = 0; i < ((List<?>)var).size(); i++){
            Object item = ((List<?>) var).get(i);
            if(item instanceof MyObject){
                result.add((MyObject) item);
            }
        }
    }
    setItems(result);
}

谢谢大家对你的帮助!

Thanks everyone for your help!

这篇关于类型安全:未选中从Object转换到列表&LT;&MyObject的GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆