Is it possible to create an open-end array?

I was wondering if I can create an array without entering a value. I donโ€™t quite understand how they work, but I am doing an inventory program and I want my array to be configured so that the user can enter the products and the variables associated with them until they are executed, then he needs to use the method for calculating the total value of all products. What would be the best way to do this?

+4
source share
5 answers
+6
source

Yes you can do it. Instead of using an array of primitive types, such as new int[10] , use something like the Vector class or perhaps ArrayList (checkout API docs for differences). Using an ArrayList is as follows:

 ArrayList myList = new ArrayList(); myList.add("Item 1"); myList.add("Item 2"); myList.add("Item 3"); // ... etc 

In other words, it grows dynamically when you add something to it.

+3
source

As Orbit pointed out, use ArrayList or Vector for your data warehouse requirements, they donโ€™t need a specific size for the purpose at the time of declaration.

+1
source

You should check out the Java Collections Framework, which includes an ArrayList, as others have pointed out. Itโ€™s good to know which other objects in the collection are available, as they may better suit your needs than others for specific requirements. For example, if you want to make sure your "list" does not contain duplicate elements, this may be a response to a HashSet.

http://download.oracle.com/javase/tutorial/collections/index.html

0
source

Other answers have already said how to do it right. For completeness in Java, each array has a fixed size (length), which is determined at creation and never changes. (An array also has a component type that never changes.)

So, you will need to create a new (larger) array when your old array is full, and copy the old content. Fortunately, the ArrayList class does this for you when its internal support array is full, so you can focus on the actual business task.

0
source

Source: https://habr.com/ru/post/1342371/


All Articles