我正在努力实现Tom Nichols的低通滤波器。 我的方法是这样的,但即使我已经防范它,我仍然会一直处于出界状态:
private float filterValue(LinkedList<Float> listOfItems)
{
final float ALPHA = 0.2f;
float filtered;
int marker = listOfItems.size();
if (listOfItems.size()>2)
marker = listOfItems.size() - 1;
float current = listOfItems.pollLast();
float previous = listOfItems.get(marker); <<-- line 282
filtered = (float) previous + ALPHA*(current - previous);
return filtered;
}
错误日志:
12-16 15:54:51.148: E/AndroidRuntime(2055): FATAL EXCEPTION: main
12-16 15:54:51.148: E/AndroidRuntime(2055): java.lang.IndexOutOfBoundsException
12-16 15:54:51.148: E/AndroidRuntime(2055): at java.util.LinkedList.get(LinkedList.java:519)
12-16 15:54:51.148: E/AndroidRuntime(2055): at se.macke.velocitysensor.SensorActivity$MySensorEventListener.filterValue(SensorActivity.java:282)
12-16 15:54:51.148: E/AndroidRuntime(2055): at se.macke.velocitysensor.SensorActivity$MySensorEventListener.getAccelerometer(SensorActivity.java:249)
12-16 15:54:51.148: E/AndroidRuntime(2055): at se.macke.velocitysensor.SensorActivity$MySensorEventListener.onSensorChanged(SensorActivity.java:231)
12-16 15:54:51.148: E/AndroidRuntime(2055): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
12-16 15:54:51.148: E/AndroidRuntime(2055): at android.os.Handler.dispatchMessage(Handler.java:99)
建议,请。
/ M
答案 0 :(得分:3)
if (listOfItems.size()<2)
marker = listOfItems.size() - 1;
如果listOfItems.size()
为零,那么var marker
将为-1会导致IndexOutOfBoundsException
。
你应该下限> 0
。
if (listOfItems.size()>0 && listOfItems.size()<2)
marker = listOfItems.size() - 1;
答案 1 :(得分:2)
Size返回列表的实际大小,它不是零索引。 get方法从列表中检索使用基于零的索引的项。保护条件不会阻止此问题。
int marker = listOfItems.size(); //assume size = 3,
if (listOfItems.size()<2) //condition is not met.
marker = listOfItems.size() - 1;
float previous = listOfItems.get(marker); //attempts to access non-existent index of 3
<强>修正强>
private float filterValue(LinkedList<Float> listOfItems)
{
final float ALPHA = 0.2f;
float filtered;
int marker = listOfItems.size();
if (listOfItems.size() > 0){
marker = listOfItems.size() - 1;
float current = listOfItems.pollLast();
float previous = listOfItems.get(marker); <<-- line 282
filtered = (float) previous + ALPHA*(current - previous);
}
return filtered;
}