gpt4 book ai didi

java - ArrayList 的 IndexOutOfBoundException

转载 作者:太空宇宙 更新时间:2023-11-04 12:28:31 26 4
gpt4 key购买 nike

我的代码

public List<GeoPoint> compute_polygon(List<GeoPoint> waypoints, double d)
{
int N = waypoints.size();//25
int T = 2 * N - 1;//49
// GeoPoint[] reduced_waypoints = waypoints.toArray(new GeoPoint[waypoints.size()]);
List<GeoPoint> polygon = new ArrayList<GeoPoint>(T);
for (int i = 1; i < N - 1; i++)
{

GeoPoint M = get_disp(waypoints.get(i - 1), waypoints.get(i), waypoints.get(i + 1), d);
polygon.add(i, v_add(waypoints.get(i), M));// here it fails and throws exception.
polygon.add(T-i, v_sub(waypoints.get(i), M));
}
}

错误输出

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.set(ArrayList.java:444)
at de.carbook.vendor.search.PathPolygon.compute_polygon(PathPolygon.java:40)
at de.carbook.vendor.search.Cleansing_the_waypoints.main(Cleansing_the_waypoints.java:41)

我无法找出导致问题的原因。

错误位于 polygon.add(i, v_add(waypoints.get(i), M));这里失败并抛出异常。

我试过polygon.add(index,element)polygon.set(index,element)两种情况都失败了

在调试时我发现了这一行 List<GeoPoint> polygon = new ArrayList<GeoPoint>(T);初始化为 null(空)。有问题吗?

更新1

public List<GeoPoint> compute_polygon(List<GeoPoint> points, double d)
{
int N = points.size();//25
int T = 2 * N - 1;//49
GeoPoint[] waypoints = points.toArray(new GeoPoint[N]);
GeoPoint[] polygon = new GeoPoint[T];
for (int i = 1; i < N - 1; i++)
{
GeoPoint M = get_disp(waypoints[i - 1], waypoints[i], waypoints[i + 1], d);
polygon[i] = v_add(waypoints[i], M);
polygon[T - i] = v_sub(waypoints[i], M);
}
GeoPoint A = v_mul(v_nor(v_prp(v_sub(waypoints[1], waypoints[0]))), d);
GeoPoint B = v_mul(v_nor(v_prp(v_sub(waypoints[N-1], waypoints[N-2]))), d);
polygon[0] = v_add(waypoints[0], A); polygon[T] = v_sub(waypoints[0], A);
polygon[N - 1] = v_add(waypoints[N-1], B); polygon[N] = v_sub(waypoints[N-1], B);

List<GeoPoint> poly = new ArrayList<GeoPoint>(Arrays.asList(polygon));
System.out.println(poly);

return poly;
}

更新错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 49
at de.carbook.vendor.search.PathPolygon.compute_polygon(PathPolygon.java:67)
at de.carbook.vendor.search.Cleansing_the_waypoints.main(Cleansing_the_waypoints.java:41)

最佳答案

这是因为您试图在一个不存在的特定索引处插入。 List<GeoPoint> polygon = new ArrayList<GeoPoint>(T);只是告诉它应该在内存中占据这么大的大小。如果不提及容量,则随着列表的增长,内部数组将不得不重复重新分配。

使用这个:

polygon.add( v_add(waypoints.get(i), M)) 

关于java - ArrayList 的 IndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38138826/

26 4 0