将ArrayList分配给java中的List
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了将ArrayList分配给java中的List,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2303字,纯文字阅读大概需要4分钟。
内容图文
![将ArrayList分配给java中的List](/upload/InfoBanner/zyjiaocheng/726/034cfe26ff2e4c53be8c56ef2c3ed91e.jpg)
我正在实现可以考虑以下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);
}
这是我的classe:比萨饼
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
列表ingredientiMargherita = pizzaMargherita;
所以我不知道如何使用operator =将ArrayList转换为List,我无法修改junit测试代码.
解决方法:
如果您无法修改作业,则必须执行以下操作:
public class Pizza implements List {
...
}
或类似的东西,比如
public class Pizza extends AbstractList {
...
}
内容总结
以上是互联网集市为您收集整理的将ArrayList分配给java中的List全部内容,希望文章能够帮你解决将ArrayList分配给java中的List所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。