android 内存不足导致内存泄露,android - ArrayList.add()导致内存不足错误? - 堆栈内存溢出...

作者分享了一次遇到Java ArrayList内存不足错误的经历,当尝试计算历史数据的n天移动平均值时,代码在添加初始占位0时崩溃。文章探讨了可能的原因,如长数字格式影响,同时寻求读者对于内存管理优化的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天,我第一次遇到内存不足错误。 我试图计算一些数据到ArrayList中的移动平均值,并且在第一步.add()时崩溃了。 方法如下所示

public ArrayList getNdaySMA(List history, int range){

long sum =0;

long SMA = 0;

ArrayList SMAs = new ArrayList();

//realRange is made due to the differences in defining "range in calculation vs speech

//a 10 day range for day 9 is actually from prices of day0 to day9, inclusive

int realRange =range-1;

//First step, add in placeholder 0s for the days within the range that have no value

//so if 10 day range, we have 0-> 9

for (int i=0;i

SMAs.add(i,0L);

}

//Next, actually calculate the SMAs for i.e. day 10

for (int i =0;i

//should be k<10, 0......9 = 10 days

for(int k=i+realRange;k==i;k--){

//Sum first from k=i+range-1 , go down to i.

//This should give us a value of RANGE

sum +=history.get(k).getClose().longValue();

}

//after summing up, we add calculate SMA and add it to list of SMAs

SMA = sum/range;

//we add the corresponding SMA to index i+range, made up of values calculated from before it

//to excel

SMAs.add(i+realRange,SMA);

sum =0;

}

return SMAs;

}

stacktrace如下

java.lang.OutOfMemoryError

at java.util.ArrayList.add(ArrayList.java:154)

at com.xu.investo.MethodDatabase.getNdaySMA(MethodDatabase.java:46)

第46行指的是

SMAs.add(i,0L);

是否由于使用长数字格式而发生此错误? 欢迎任何建议。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值