类型安全:从 Object 到 List<MyObject> 的未经检查的强制转换 [英] Type safety: Unchecked cast from Object to List&lt;MyObject&gt;

查看:19
本文介绍了类型安全:从 Object 到 List<MyObject> 的未经检查的强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ListView 列出了一个自定义对象(比如 MyObject).

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

我想通过 EditText 动态过滤它,所以我必须使用 publishResults 方法实现一个 getFilter():

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 抱怨:Type safety: Unchecked cast from Object to List

At this point, Eclipse complains: Type safety: Unchecked cast from Object to List<MyObject>

我确信这个转换永远是正确的,但 Eclipse 只建议添加 @SuppressWarnings("unchecked") 但我完全反对 SuppressWarnings 因为它只是隐藏问题,而不是解决方案...

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

无法对参数化类型 List 执行 instanceof 检查.使用表单 List

我知道转换总是正确的,但哪种方法可以让代码确保 results.values 实际上是一个 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> ?

提前致谢!

推荐答案

好吧,我终于找到了解决方案.

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() 方法中使用它,使用 Object 参数而不是 List 以确保

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

结果代码如下:

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

感谢大家的帮助!

这篇关于类型安全:从 Object 到 List<MyObject> 的未经检查的强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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