Из OpenCV4, findContours
возвращает 2 значения contours
и hierachy
, поэтому теперь контуры находятся в new
в вашем коде. Это должно быть
cnts, hier = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
Вы можете получить пустой список типа Foo с помощью следующего синтаксиса:
return Collections.<Foo>emptyList().iterator();
Я бы пошел по принципу
public Iterator<Foo> iterator() {
if (underlyingData == null)
return Collections.<Foo> emptyList().iterator();
return underlyingData.iterator();
}
Просто, обработайте специальный случай и вернитесь, затем обращаться с нормальным случаем. Но моя главная мысль в том, что вы можете избежать назначения с помощью
Collections.<Foo> emptyList().iterator();
I guess this shows that Java type inference doesn't work in every case and that the ternary operator is not always equivalent to the apparently equivalent if-else construct.
I also want to state avoid null
. Also avoid passing Iterator
s about, because they have strange stateful behaviour (prefer Iterable
). However, assuming you have a legitimate, non-premature reason for doing this, my preferred way of writing it would be
public Iterator<Foo> iterator() {
return getUnderlyingData().iterator();
}
private List<Foo> getUnderlyingData() {
if (underlyingData == null) {
return Collections.emptyList();
} else {
return underlyingData;
}
}
IMO, it's better not to insert the inferable type information if it can be inferred (even if it makes your code longer).
You are almost certainly going to do it more than once, so insert a getUnderlyingData
method instead of just declaring a local variable.
You are calling iterator
on both results, so do not repeat yourself.
Извините, я понял это. Вам нужно использовать присвоение, чтобы компилятор мог определить параметризованный тип.
public Iterator<Foo> iterator() {
if (underlyingData != null) {
return underlyingData.iterator();
} else {
List<Foo> empty = Collections.emptyList(); // param type inference
return empty.iterator();
}
}
Раздражают Коллекции.
- основная причина, по которой мы предоставляем Iterators.emptyIterator ()
в Google-коллекции . В таких случаях, как ваш, параметр типа не требуется.