是可以接受返回unmodifiableList还是应该返回数组? [英] Is it acceptable to return unmodifiableList or should I return array?

查看:175
本文介绍了是可以接受返回unmodifiableList还是应该返回数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有方法 List< Foo> getFoos(),它从远程服务器获取数据并返回。

I have method List<Foo> getFoos () which gets the data from remote server and returns it.

当然,用户不应该更改列表中的项目数因为他会得到不与服务器上的数据同步的数据(如果他想要改变项目数量,他有特殊的方法,例如 addFoo())。

Of course, user shouldn't change number of items of the list because he'll get data not synchronized with data on the server (and if he want change number of items he has special methods like addFoo ()).

第一种方法是将数组和更改方法的签名返回到 Foo [] getFoos()。但是在Java中更常见,更方便用户操作集合,所以我将签名更改为 List< Foo> getFoos()。此方法总是返回

First approach was to return array and change method's signature to Foo[] getFoos (). But it's more common in java and more convenient to user to operate with collections so I changed signature to List<Foo> getFoos (). This method always returns

Collections.unmodifiableList(originalList)

所以,当用户尝试更改列表时,他会得到RuntimeException。

So, when user try to change the list he will get RuntimeException.

在类似情况下,有没有关于api设计的建议?

Are there any recommendations about api design in similar cases?

推荐答案

Collections.unmodifiableList如果完全可以接受,应该更快(不需要创建数组)。

Collections.unmodifiableList if perfectly acceptable, and should be faster (no need to create an array).

编辑 - 在API设计方面,你应该让你的javadoc清楚!使用方法而不阅读其文档的人应该得到惊喜:p

Edit - In terms of API design, you should just make your javadoc clear ! People who use a method without reading its doc deserve the surprise :p

这篇关于是可以接受返回unmodifiableList还是应该返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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