【问题标题】:A few objects into one Array几个对象成一个数组
【发布时间】: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的轮子。

标签: java arrays object


【解决方案1】:

创建后

List<Vertext> vertexList = new ArrayList<>();

并且添加东西而不用担心限制,你可以

Vertex[] vertexArray = vertexList.toArray( new Vertex[vertexList.size()] );

一切都会好起来的。

(对于未来:与 List 相比,基于数组的代码有缺点 - 正如您现在所注意到的那样。)

【讨论】:

  • 确实如此。最简单的方法是使用数组列表,只要您不知道最终大小,最后使用 vertexList.toArray() 将列表转换为数组(无需参数)。
【解决方案2】:

你的代码

A.adjacencies = new Edge[] { new Edge(M, 8) };

创建大小为1的数组。数组的大小在创建数组时确定,以后不能更改。如果需要,您可以创建新数组并将元素从旧数组复制到新数组。 (这是对 ArrayList 实现的粗略描述)。

如果你事先知道数组的大小,那就做

A.adjacencies = 新边[大小]; A.adjacencies[0]=新边(M, 8); ... A.adjacencies[size-1]=new Edge(M, 不管);

因为你从文件中读取,你应该知道你的数据结构的大小。大多数文件格式首先存储动态结构的大小,然后存储结构的元素。

如果您事先不知道结构的大小,那么动态数据结构(在您的情况下为java.util.List)是唯一合理的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    相关资源
    最近更新 更多