问题
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