是否可以创建一个开放式数组?
我想知道是否可以创建一个数组而无需输入值。我不完全理解它们是如何工作的,但我正在做一个库存程序,并希望以用户可以输入产品及其相关变量直到完成的方式设置我的数组,然后它需要使用计算所有产品总成本的方法。最好的方法是什么?
I was wondering if I could create an array without having to enter a value. I don't fully understand how they work, but I'm doing an inventory program and want my array to be set up in a way that the user can enter products and their related variables until they are done, then it needs to use a method to calculate the total cost for all the products. What would be the best way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用数组列表。
这将允许您创建动态数组。
http://download.oracle.com/javase /1.5.0/docs/api/java/util/ArrayList.html
这是一个示例/概述:
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Use an ArrayList.
This will allow you to create a dynamic array.
http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html
Here is an example/overview:
http://www.anyexample.com/programming/java/java_arraylist_example.xml
是的,你可以这样做。不要使用原始类型数组,例如
new int[10]
,而是使用 Vector 类或 ArrayList 之类的东西(查看 API 文档以了解差异)。使用 ArrayList 看起来像这样:换句话说,当您向其中添加内容时,它会动态增长。
Yes, you can do this. Instead of using a primitive type array, for example
new int[10]
, use something like the Vector class, or perhaps ArrayList (checkout API docs for the differences). Using an ArrayList looks like this:In other words, it grows dynamically as you add things to it.
正如 Orbit 指出的,使用 ArrayList 或 Vector 来满足您的数据存储需求,它们不需要在声明时分配特定的大小。
As Orbit pointed out, use ArrayList or Vector for your data storage requirements, they don't need specific size to be assigned while declaration.
您应该熟悉 Java 集合框架,正如其他人指出的那样,其中包括 ArrayList。最好知道还有哪些其他集合对象可用,因为对于某些要求,一个集合对象可能比另一个集合对象更适合您的需求。例如,如果您想确保您的“列表”不包含重复元素,则 HashSet 可能就是答案。
http://download.oracle.com/javase/tutorial/collections/index.html
You should get familiar with the Java Collections Framework, which includes ArrayList as others have pointed out. It's good to know what other collection objects are available as one might better fit your needs than another for certain requirements. For instance, if you want to make sure your "list" contains no duplicate elements a HashSet might be the answer.
http://download.oracle.com/javase/tutorial/collections/index.html
其他答案已经告诉了如何做正确的事情。为了完整起见,在 Java 中,每个数组都有一个固定的大小(长度),该大小在创建时确定并且永远不会改变。 (数组还有一个永远不会改变的组件类型。)
因此,当旧数组已满时,您必须创建一个新的(更大的)数组,并将旧内容复制过来。幸运的是,当 ArrayList 类的内部支持数组已满时,它会为您执行此操作,因此您可以专注于手头的实际业务任务。
The other answers already told how to do it right. For completeness, in Java every array has a fixed size (length) which is determined at creation and never changes. (An array also has a component type, which never changes.)
So, you'll have to create a new (bigger) array when your old array is full, and copy the old content over. Luckily, the ArrayList class does that for you when its internal backing array is full, so you can concentrate on the actual business task at hand.