gpt4 book ai didi

java - 将 ArrayList 分配给 Java 中的列表

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:44:22 25 4
gpt4 key购买 nike

我正在实现可以考虑以下 junit 测试的代码:

package it.unica.pr2.pizze.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.*;
import it.unica.pr2.pizze.*;

@RunWith(JUnit4.class)
public class TestPizza {

@Test
public void test1() {
Ingrediente mozzarella = new Ingrediente("mozzarella",50);
Ingrediente pomodoro = new Ingrediente("pomodoro",10);
Ingrediente[] ingredienti = new Ingrediente[] {mozzarella, pomodoro}
Pizza pizzaMargherita = new Pizza(ingredienti);
assertTrue( pizzaMargherita.calorie() == 60 );
List ingredientiMargherita = pizzaMargherita;
assertTrue(ingredientiMargherita.size() ==2);
assertTrue(ingredientiMargherita.get(0) == mozzarella);
assertTrue(ingredientiMargherita.get(1) == pomodoro);
}

这是我的类(class):披萨

package it.unica.pr2.pizze;
import java.util.ArrayList;
import java.util.List;

public class Pizza {


private ArrayList<Ingrediente> ingredienti;


public Pizza(Ingrediente[] ing) {

this.ingredienti = new ArrayList<>();

int i = 0;
while (i < ing.length) {

this.ingredienti.add(ing[i]);
i++;
}

}

public double calorie(){

double sumaCalorie = 0;

for(Ingrediente elem: this.ingredienti)
sumaCalorie += elem.getCalorie();

return sumaCalorie;

}
}

还有一个类:Ingrediente

package it.unica.pr2.pizze;


public class Ingrediente {


private String nomeIngrediente;
private double calorie;



public Ingrediente(String nomeIngrediente, double calorie) throws IngredienteNonValidoException {

this.nomeIngrediente = nomeIngrediente;
if (calorie < 0) throw new IngredienteNonValidoException();
else
this.calorie = calorie;
}

public void setNomeIng(String nomeIngrediente) {
this.nomeIngrediente = nomeIngrediente;
}

public void setCalorie(double calorie) {

this.calorie = calorie;
}

public String getNomeIng() {

return this.nomeIngrediente;
}

public double getCalorie() {
return this.calorie;
}

}

运行测试后出现如下错误:

错误:类型不兼容:无法将 Pizza 转换为 List

列出成分iMargherita = pizzaMargherita;

所以我不知道如何仅使用运算符=将ArrayList转换为List,我无法修改junit测试代码。

最佳答案

如果你不能修改作业,你必须这样做:

public class Pizza implements List {
...
}

或者类似的东西,比如

public class Pizza extends AbstractList {
...
}

关于java - 将 ArrayList 分配给 Java 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30517461/

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