gpt4 book ai didi

java - 将集合中的泛型类型与同一类型 java 进行比较

转载 作者:行者123 更新时间:2023-11-29 07:29:59 25 4
gpt4 key购买 nike

    public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
Box<String> box = null;
List<Box> boxes = new ArrayList<>();
for (int i = 0; i < n; i++) {
box = new Box<>(scanner.nextLine());
boxes.add(box);
}
box = new Box<>(scanner.nextLine());
Box.count(boxes, box);
}

我在这里创建盒子并将它们传递给盒子类中的静态方法

public class Box<T> {
private T name;

public Box(T name) {
this.name = name;
}

public static <E> int count(List<E> list, E compeer) {
int counter = 0;
for (E el : list) {
if (el.compearTo(compeer) < 0) { // ofc it doesnt works compearTo is red caus i am not extending Comperable
counter++;
}
}
return counter;
}
}

在框计数方法中,我必须计算有多少元素“低于”该方法的第二个参数,但我无法比较其中的任何内容...我知道通用类型必须扩展 Comperable <E extends Comparable>为此,如果我输入 <E extends Comparable>在我的 Box.count方法然后我不能传递参数。

最佳答案

but if I type <E extends Comparable> in my Box.count method then i cant pass the arguments.

不能传递参数的原因是因为Box不执行Comparable .

您应该做的是在 Box 中添加通用约束类:

class Box<T extends Comparable<T>> { ... }

此外,您的 count方法有点通用。如果 compeer 可能更有意义的类型更改为 Box<T>listList<Box<T>> .

方法签名现在看起来像这样:

public static <T extends Comparable<T>> int count(List<Box<T>> list, Box<T> compeer) {

你可以像这样实现这个方法:

return (int)list.stream().
filter(x -> x.name.compareTo(compeer.name) < 0).count();

关于java - 将集合中的泛型类型与同一类型 java 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44195142/

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