Return empty Vector collection instead of null

こ雲淡風輕ζ 提交于 2019-12-13 22:26:51

问题


I have a function that returns a Vector and in case of an error, I want to return an empty Vector which can be checked using Collections.isEmpty by the calling method. But I am unable to find the way to do it as Collections provides Collections.emptyList functions for List, Maps, etc. but not for Vector and I am forced to return null by function which I want to avoid.

How to achieve this?


回答1:


You could return a new Vector<X>(), but a better solution would be to move away from Vector which has been obsolete for (many) years. Unless you require concurrency features, you can use an ArrayList instead.

You added that you receive the Vector from a third party service. Don't forget that a Vector is a List, so you could maybe use something like this:

public List<X> getData() {
  try {
    Vector<X> v = getDataFromService();
    return v;
  } catch (ServiceException e) {
    return Collections.emptyList();
  }
}



回答2:


I want to return an empty Vector which can be checked using Collections.isEmpty

Do you want to return an empty Vector or do you want Collections.isEmpty() to return true when passed an empty Vector?
Generally, returning an empty Vector would indicate no error but an empty result - you should consider throwing a (checked) exception on an error - that will make the contract between the method and its caller clearer. If, at some later date, you want the method to be able to return an empty Vector to indicate an empty result (and no error) you will be able to without changing all the calling code.




回答3:


Can't you use its own method?

 return vector.isEmpty() ? new Vector<?>() : vector;


来源:https://stackoverflow.com/questions/54220769/return-empty-vector-collection-instead-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!