【发布时间】:2015-01-05 12:23:03
【问题描述】:
我在将新对象添加到对象数组时遇到问题。 看:
A.adjacencies = new Edge[] { new Edge(M, 8) };
这是一个示例,其中 Edge[] 由一个 Object 组成。但我不知道 Edge[] 将包含多少对象,因为我从 File 中获取数字。我将“顶点”从文件带到顶点 [],并将工资从文件带到工资 []。 该文件如下所示:
1 2 3
3 4 5
3 2 1
4 56 7
2 3 5
5 2 1
每行的第一个和第二个数字是顶点,第三个是工资。
我写过这样的代码:
Vertex[] vertices = new Vertex[N];
for(int i=0; i<N; i++)
vertices[i] = new Vertex(i);
int w_1 = Vertex[0], w_2 = 0, wage = 0;
for(int i=0; i<Vertex.length; i++) {
if(Vertex[i] == w_1) {
if(i%2 == 0) {
if(wage == 0) wage = Wage[i/2];
if(i%2 == 0) {
for(int f=0; f<vertices.length; f++)
if(vertices[f].name == i) {
for(int l=0; l<vertices.length; l++)
if(vertices[l].name == Vertex[i+1])
vertices[f].adjacencies = new Edge[] { new Edge(vertices[l], wage) };
}
}
if(i%2 != 0) {
for(int f=0; f<vertices.length; f++)
if(vertices[f].name == i) {
for(int l=0; l<vertices.length; l++)
if(vertices[l].name == Vertex[i-1])
vertices[f].adjacencies = new Edge[] { new Edge(vertices[l], wage) };
}
w_1 = i;
int temp = Wage[i/2];
if(temp < wage) {
wage = temp;
if(i%2 == 0)
w_2 = Vertex[i+1];
if(i%2 != 0)
w_2 = Vertex[i-1];
}
}
}
}
我该如何解决这个问题,将几个对象插入一个数组而不知道会有多少个对象? :) 我不能使用 ArrayList。
【问题讨论】:
-
为什么不能,因为性能问题?
-
因为那剩下的代码不能正常工作。
-
了解如何使用列表。
-
看来你是在重新发明ArrayList的轮子。