热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何从文件中定义给定大小的数组?-Howtodefineanarraywithgivensizefromafile?

Icreatedaclass,andIwanttocreatesomeglobalarraysforthisclassinordertoallowallmeth

I created a class, and I want to create some global arrays for this class in order to allow all methods of the class to use them. Problem is I don't know the size of the arrays in the first place. The size is based upon a file I read using JAVA's code. How can I define those arrays (Global) with the information I receive from the file?

我创建了一个类,我想为这个类创建一些全局数组,以便允许类的所有方法使用它们。问题是我首先不知道数组的大小。大小基于我使用JAVA代码读取的文件。如何使用从文件中收到的信息定义这些数组(全局)?

**Got no problem with reading the file itself and retrieve information from it.

**读取文件本身并从中检索信息没有问题。

Thanks :)

谢谢 :)

1 个解决方案

#1


1  

UPDATE: According to your comment, I had misunderstood your needs.

更新:根据你的评论,我误解了你的需求。

If your problem is just the array declaration, then this should probably solve it.

如果您的问题只是数组声明,那么这应该可以解决它。

You may declare your 2D-array this way as a "global" array(*):

您可以将这种2D数组声明为“全局”数组(*):

private MyClass[][] myArray;

This won't initialize it, but declare its type as a 2D-array of MyClass objects.

这不会初始化它,而是将其类型声明为MyClass对象的2D数组。

Then when you start reading the file and you've got the size:

然后,当你开始阅读文件,你已经有了大小:

int size = /* read the size from the file */;
myArray = new MyClass[size][size];

It is unclear what you want to achieve.

目前还不清楚你想要达到什么目标。

If you want to dynamically add elements to an array and you don't know its size at initialization time, I would suggest you use an ArrayList:

如果你想动态地向数组添加元素而你在初始化时不知道它的大小,我建议你使用一个ArrayList:

ArrayList list = new ArrayList<>();

To add an element:

要添加元素:

list.add(element);

To access element at index i:

要访问索引i处的元素:

SomeClassForYourData element = list.get(i);

To find the size of the structure:

要查找结构的大小:

int size = list.size();

推荐阅读
author-avatar
朱永红2602897625
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有