返回空的Vector集合

返回空的Vector集合

本文介绍了返回空的Vector集合,而不是null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回Vector的函数,如果发生错误,我想返回一个空的Vector,可以通过调用方法使用Collections.isEmpty对其进行检查.但是我找不到方法,因为Collections为List,Maps等提供了Collections.emptyList函数,但没有为Vector提供,因此我被迫避免使用该函数返回null.

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.

如何实现?

推荐答案

您可以返回一个 new Vector< X>(),但是更好的解决方案是远离 Vector(已经有很多年了).除非需要并发功能,否则可以使用 ArrayList .

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.

您还添加了从第三方服务收到的 Vector .不要忘了 Vector List ,因此您可以使用以下代码:

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

这篇关于返回空的Vector集合,而不是null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:36