gpt4 book ai didi

java - 从原始 ArrayList 获取值

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

我有一个 ArrayList 未指定为 double / float ,但它包含 double 浮点值 22.33 , 12.56 , 34 , 21 ...

当我从文件中读取数据以将数据保存到其中时,我实际上有两个。他们看起来像这样

static List<MySample> data = new ArrayList<MySample>();
static ArrayList list = new ArrayList();

ArrayList<Double> list = new ArrayList();我可以用一个简单的像这样循环:

double sum = 0;
double count = 0;
for (Double a : list) {
sum += a;
count++;
}
System.out.println("Average is " + sum / count);

但是当我使用时:

for (Object o : list) {
// How can I do the same with some code here?
}

我怎样才能对 Object 做同样的事情?环形?我希望你确实理解我的问题。

好的,这是我反序列化文件并从中获取值的方法...

public void deserialize(List<MySample>listan, String path) {
double sum=0;
int count=0;
try {File file = new File(path);ObjectInputStream in = new
ObjectInputStream(newFileInputStream(file));
listan = (ArrayList<MySample>) in.readObject();


for(Object obj: listan){

//here I need the code
}
System.out.println("Good work!");
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}

}

最佳答案

如果你确保list包含所有 double 值,将其转换为 Double (为了不破坏整个循环,必须将 try/catch 放在循环中......它可能不是高性能):

for (Object o : list) {
try {
sum += ((Double)o).doubleValue();
count++;
} catch(ClassCastException e) {
}
}

但建议不要使用像ArrayList list = new ArrayList(); 这样的原始类型列表。 , 更好的方法是 List<Double> list = new ArrayList<Double>(); .

关于java - 从原始 ArrayList 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30304228/

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