阿波羅的戰(zhàn)車(chē)
2023-05-10 14:14:59
我正在嘗試編譯一位前同事的代碼,但它說(shuō)該方法unmodifiableList()不能應(yīng)用于給定類(lèi)型。Eclipse 中的代碼沒(méi)有顯示任何錯(cuò)誤。但它仍然不讓我編譯它。可能是什么錯(cuò)誤?package framework.interview.demographics;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Objects;import java.util.stream.Collectors;import java.util.stream.Stream;import org.apache.xmlbeans.impl.xb.xsdschema.Public;import framework.data.people.NonReference;import framework.data.people.people;public class schedualData { private final List<people> schedual; private schedualData(List<people> schedual) { this.schedual = Objects.requireNonNull(schedual); } public static schedualData getSchedualData(List<people> schedual) { if(schedual.size() < 1) throw new IllegalArgumentException("schedual must contain at least one people"); if(Stream.of(schedual).filter(people -> (!(people instanceof NonReference))).count() != 1) throw new IllegalArgumentException("There must be one and only one Reference between" + "People, number, and Review"); return new schedualData(schedual); } //****** Getters ******\\ public people getReference() { return schedual.stream() .filter(people -> !(people instanceof NonReference)) .toArray(people[]::new)[0]; } public List<NonReference> getNonReferenceschedual() { //This is where the error is showing. return Collections .unmodifiableList(schedual.stream() .filter(NonReference.class::isInstance) .map(x -> (NonReference) x) .collect(Collectors.toCollection (ArrayList<NonReference>::new))); } public List<people> getFullschedual() { return Collections.unmodifiableList(schedual); } public int size() { return schedual.size(); }}
1 回答

千巷貓影
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
您需要顯式聲明泛型類(lèi)型參數(shù)。由于某種原因*,無(wú)法推斷。
return Collections.<NonReference>unmodifiableList(schedual.stream() .filter(NonReference.class::isInstance) .map(NonReference.class::cast) .collect(Collectors.toCollection(ArrayList::new)));
或者
return Collections.unmodifiableList(schedual.stream() .filter(NonReference.class::isInstance) .map(NonReference.class::cast) .collect(Collectors.<NonReference, List<NonReference>>toCollection(ArrayList::new)));
或者
ArrayList<NonReference> result = schedual.stream() .filter(NonReference.class::isInstance) .map(NonReference.class::cast) .collect(Collectors.toCollection(ArrayList::new)); return Collections.unmodifiableList(result);
雖然,你可以簡(jiǎn)單地去
return Collections.unmodifiableList(schedual.stream() .filter(NonReference.class::isInstance) .map(NonReference.class::cast) .collect(Collectors.toList()));
*問(wèn)題在于,它Collections.unmodifiableList
決定了 的類(lèi)型collect(Collectors.toCollection())
,而不是相反,正如您可能期望的那樣。
您可以通過(guò)準(zhǔn)確說(shuō)明您想要的內(nèi)容來(lái)幫助編譯器進(jìn)行類(lèi)型推斷。你說(shuō)要么unmodifiableList
拿走什么,.collect(Collectors.toCollection())
要么返回什么。
上面提到的四個(gè)片段中的任何一個(gè)都可以幫助您解決問(wèn)題。
x -> (NonReference) x
可以替換為NonReference.class::cast
.
添加回答
舉報(bào)
0/150
提交
取消