作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
我是一名优秀的程序员,十分优秀!