在java中的Collections.checkedList()调用是什么? [英] What is the Collections.checkedList() call for in java?

查看:2186
本文介绍了在java中的Collections.checkedList()调用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道 java.util.Collections.checkedList()实际上是用的。

I just want to know for what java.util.Collections.checkedList() is actually used.

我有一些代码,我知道是返回一个 List< String> ,但它是通过一个链的消息传递呼叫,并作为 java.io.Serializable 返回给我。是checkListList调用好我把我的 Serializable 变成 List< String> ?我知道我可以把它转换为 java.util.List ,但我不想检查每个元素,我不舒服,假设每个元素是一个 String

I have some code that I know is returning me a List<String> but it's being passed through a chain of messaging calls and returned to me as a java.io.Serializable. Is that checkedList call good for me to turn my Serializable into a List<String>? I know I can cast it to a java.util.List, but I'd rather not have to check each element and I'm not comfortable with assuming each element is a String.

推荐答案

它部分用作调试工具找到代码插入错误类型的类,如果你看到发生了,但不能弄清楚在哪里。

It is used in part as a debugging tool to find where code inserts a class of the wrong type, in case you see that happening, but can't figure out where.

你可以使用它作为公共的一部分API,它提供了一个集合,你想确保集合没有得到任何错误的类型(如果例如客户端删除泛型)。

You could use it as part of a public API that provides a collection and you want to ensure the collection doesn't get anything in it of the wrong type (if for example the client erases the generics).

在你的情况下,你可以使用它的方式是:

The way you could use it in your case is:

 Collections.checkedList(
      new ArrayList<String>(uncertainList.size()), String.class)
      .addAll(uncertainList);

如果这不会引发异常,那么你就知道你是好的。这不是一个性能优化的代码段,但如果列表内容相当小,应该很好。

If that doesn't throw an exception, then you know you are good. That isn't exactly a performance optimized piece of code, but if the list contents are reasonably small, it should be fine.

这篇关于在java中的Collections.checkedList()调用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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