gpt4 book ai didi

java - 推理变量 T 在使用 .collect(toList()) 时具有不兼容的边界

转载 作者:行者123 更新时间:2023-11-30 08:08:21 25 4
gpt4 key购买 nike

任务是:

Modify bonuses for all workers whose name starts with a letter from the second half of the alphabet.

class Worker that extends Employee
{
public Worker(String name, int yOfEmp, int salary, Manager boss){
super(name, yOfEmp, salary,boss);
boss.addEmployee(this);
}

public float getBonus(Employee emp){
Random rand = new Random();
float proc = rand.nextFloat();
return emp.getSalary() * proc;
}
public float setBonus(Employee e, float proc){
float newProc = proc;
return e.getSalary() * proc;
}

@Override
public String toString() {
return super.toString();
}
}

class RegWorker extends Worker
{
}

class Main
{
public static void main(String[] str) {
Manager bill = new Manager("Bill", 2010, 2549, null);
Manager steven = new Manager("Steven", 2011, 2100, bill);
Trainer jerry = new Trainer("Jerry", 2014, 800, steven);
RegWorker john = new RegWorker("John", 2010, 1000, bill);
RegWorker kate = new RegWorker("Kate", 2011, 1000, bill);
RegWorker sam = new RegWorker("Sam", 2013, 1200, steven);

final List<Worker> workers = Arrays.asList(jerry, john, kate, sam);

System.out.println("Modify bonuses for all regular workers:");
RegWorker reg = null;

List<RegWorker> regWorkers = workers
.stream()
.filter(w -> w.getClass() == reg.getClass())
.filter(w -> w.getName().charAt(0) < 'O')
.map(w -> w.setBonus(w, w.getBonus(w)+3))
.collect(toList());
}

我知道了 error

reason: inference variable T has incompatible bounds
equality constraints: RegWorker
lower bounds: Float

最佳答案

当你在做 map ,您将流对象替换为映射器函数返回值,即 setBonus 的返回值, 这是 float 的。所以在map之后你有没有一步Stream<RegWorker> ,但是Stream<Float>应该收集到 List<Float> .

看来你想用peek而不是 map .您还需要将流元素转换为 RegWorker作为您的原始流的类是 Stream<Worker> .最后请注意,您的代码还有另一个问题会在运行时出现:reg.getClass()会抛出 NullPointerException作为reg一片空白。可能你只需要 .filter(w -> w instanceof RegWorker) :

List<RegWorker> regWorkers = workers
.stream()
.filter(w -> w instanceof RegWorker)
.filter(w -> w.getName().charAt(0) < 'O')
.map(w -> (RegWorker)w)
.peek(w -> w.setBonus(w, w.getBonus(w)+3))
.collect(toList());

关于java - 推理变量 T 在使用 .collect(toList()) 时具有不兼容的边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33178661/

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