gpt4 book ai didi

java - 在 addItem 的使用中如何利用泛型并检查我的参数?

转载 作者:行者123 更新时间:2023-12-02 11:42:55 24 4
gpt4 key购买 nike

所以我得到了好消息unchecked call to addItem(E)对于 JComboBox。我熟悉常见情况,但组合框位于功能处理的列表中,但解决方案却让我困惑。精简代码示例:

public static Boolean final test(final List<JComboBox> comboboxList) {
final List<String> stuff=new ArrayList<>();
// stuff gets stuffed with stuff here
comboboxList.forEach((JComboBox combobox) -> {
combobox.removeAllItems();
stuff.forEach((contents) -> {
combobox.addItem(contents);
});
});
}

传入的 List 中的组合框均声明为 <String> ,但这似乎对 forEach 中的 addItem 没有帮助。似乎我应该在 forEach 中声明它,但我一直找不到这样做的有效语法。

最佳答案

The comboboxes in the List being passed in are all declared as , but that doesn't seem to help the addItem in the forEach.

这没有帮助,因为您没有指定 String每次使用 JComboBox 声明变量时键入类。
所以它声明 raw JComboBox ,即JComboBox<Object> .
而警告。

public static Boolean test(final List<JComboBox<String>> comboboxList) {
final List<String> stuff = new ArrayList<>();
// stuff gets stuffed with stuff here
comboboxList.forEach((JComboBox<String> combobox) -> {
combobox.removeAllItems();
stuff.forEach((contents) -> {
combobox.addItem(contents);
});
});

return someBooleanValue; // to compile
}

请注意,声明 lambda 参数的类型不是强制性的。您可以通过这种方式简化您的代码:

public static Boolean test(final List<JComboBox<String>> comboboxList) {
final List<String> stuff = new ArrayList<>();
// stuff gets stuffed with stuff here
comboboxList.forEach(combobox -> {
combobox.removeAllItems();
stuff.forEach(combobox::addItem);
});

return someBooleanValue; // to compile
}

关于java - 在 addItem 的使用中如何利用泛型并检查我的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48409904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com