Java 使用初始容量重新实例化ArrayList
我已经有两个基本上是图形数据结构的顶点数组列表。第一个是顶点或交点,第二个是边,称为道路。当我知道图形中有多少个顶点/边时,我尝试重新实例化它们Java 使用初始容量重新实例化ArrayList,java,arraylist,instantiation,Java,Arraylist,Instantiation,我已经有两个基本上是图形数据结构的顶点数组列表。第一个是顶点或交点,第二个是边,称为道路。当我知道图形中有多少个顶点/边时,我尝试重新实例化它们 int line = 0; while(reader.hasNextLine()){ String thisLine = reader.nextLine(); System.out.println(thisLine + " line: " + line);
int line = 0;
while(reader.hasNextLine()){
String thisLine = reader.nextLine();
System.out.println(thisLine + " line: " + line);
if(line == 0){
numIntersections = Integer.parseInt(thisLine.split("\\s+")[0]);
intersections = new ArrayList<Intersection>(numIntersections);
System.out.println("numIntersections: " + numIntersections + " intersections size: " + intersections.toArray().length);
numRoads = Integer.parseInt(thisLine.split("\\s+")[1]);
roads = new ArrayList<Road>(numRoads);
}
else if(line > 0 && line < numIntersections + 1){
int first = Integer.parseInt(thisLine.split("\\s+")[0]);
int second = Integer.parseInt(thisLine.split("\\s+")[1]);
int third = Integer.parseInt(thisLine.split("\\s+")[2]);
intersections.add(first, new Intersection(second, second, third));
}
else if(line > numIntersections + 1){
roads.add(new Road(intersections.get(Integer.parseInt(thisLine.split("\\s+")[0])), intersections.get(Integer.parseInt(thisLine.split("\\s+")[1]))));
intersections.get(Integer.parseInt(thisLine.split("\\s+")[0])).addNeighbor(intersections.get(Integer.parseInt(thisLine.split("\\s+")[1])));
}
line++;
}
int行=0;
while(reader.hasNextLine()){
字符串thisLine=reader.nextLine();
System.out.println(thisLine+“line:”+行);
如果(行==0){
numIntersections=Integer.parseInt(thisLine.split(“\\s+”)[0]);
交叉点=新阵列列表(numIntersections);
System.out.println(“numIntersections:+numIntersections+”交叉口大小:“+crossions.toArray().length”);
numRoads=Integer.parseInt(thisLine.split(“\\s+”)[1]);
道路=新阵列列表(numRoads);
}
else if(行>0&&line数字分段+1){
roads.add(新道路(crosss.get(Integer.parseInt(thisLine.split(\\s+)[0])),crosss.get(Integer.parseInt(thisLine.split(\\s+)[1]));
crossions.get(Integer.parseInt(thisLine.split(\\s+)[0])).addNeighbor(crossions.get(Integer.parseInt(thisLine.split(\\s+)[1]);
}
line++;
}
可以看到,在第一个if语句中,当我知道numIntersections时,我重新实例化了ArrayList。当我知道道路的数量时,我也会这样做
然而,当我试图在第一条elseif语句中向列表添加新的交集时,它抛出了一个越界异常。不应出现这种情况,因为容量设置为numIntersections。容量不等于大小 新创建的容量为10的
ArrayList
将有一个支持数组,允许分配10个元素,但其大小仍然为零。对该ArrayList
中的任何元素进行寻址将导致indexootfboundsexception
,尽管add()
方法允许您在索引0处添加元素
正如该方法的Javadoc所述:
抛出:
IndexOutOfBoundsException
-如果索引超出范围(索引<0 | |索引>大小())
显示如何使用特定数量的值初始化
ArrayList
。Hm,非常有趣。很高兴知道这一点。我如何将此标记为答案?没关系,看来我得等5分钟。非常感谢!