gpt4 book ai didi

java - Java 中整数值列表的总和 (JDK 1.7)

转载 作者:行者123 更新时间:2023-12-01 18:38:46 25 4
gpt4 key购买 nike

有人可以建议一下,如何获取前几个列表元素(整数)的总和吗?

注意:我的 Java 版本:“1.7.0_07”。

下面是代码:

    Integer sum=new Integer(0);
for(int i=0;i<3;i++)
sum=sum+list.get(i);

错误:对于参数类型 Integer、Object,运算符 + 未定义

最佳答案

我相信您已将列表声明为原始类型,即

List list = new List();

你需要做的是:

List<Integer> list = new List<Integer>();

否则每次执行 list.get() 时都必须进行类型转换

sum=sum+(Integer)list.get(i);

编辑:关于您的其他问题

If i define like --> 'List list', seeing error suggestion like "Syntax error, parameterized types are only available if source level is 1.5"

答案:

my guess would be that while you run eclipse itself with jdk 1.6, it's actually configured with a different default jre. see window->preferences->java->Installed JREs and make sure that the checked JRE is 1.6. (i'm hoping that you are getting this error while working in some IDE) if the default JRE is indeed 1.6, chances are that it's a project specific setting. see that the project is configured to use the right jre.

关于java - Java 中整数值列表的总和 (JDK 1.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20771026/

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