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?
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
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:
ArrayList myList = new ArrayList();
myList.add("Item 1");
myList.add("Item 2");
myList.add("Item 3");
// ... etc
In other words, it grows dynamically as you add things to it.
As Orbit pointed out, use ArrayList or Vector for your data storage requirements, they don't need specific size to be assigned while declaration.
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
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.
Related
Is there any way I can input data into any array list without actually doing the following in each place in the code where I need to insert data?
ArrayList<dataType> kwh = new ArrayList<dataType>();
arrayListVariable.add(data);
arrayListVariable.add(moreData);
arrayListVariable.add(evenMoreData);
As of right now, this seems to be very time consuming if I need to put in quite a bit of data into the array list. Is there a simpler/more concise way of doing this?
You could use like:
ArrayList<dataType> kwh = new ArrayList<dataType>(Arrays.asList(data, moreData, evenMoreData));
Alternatively, you could use Guava's Lists class.
To add new elements:
List<Integer> ints = Lists.newArrayList(1, 2, 3);
However, this one is not fixed size. You can add new elements just by calling ints.add() afterwards.
That depends upon what you mean by "faster".
If you're talking about how fast the program runs, the add() method runs in constant time. You're not going to get much better than that unless you use an actual array. You're using an ArrayList, though, so I'm going to assume you're willing to trade away some of the speed/space optimization for the flexibility.
If you mean "How can I add a lot of data to a list without a lot of typing", then answer is this: It depends upon what you're doing.
If you're reading from a file, create a method that splits files by whatever separator is used between data elements. Loop through these items and add them to your ArrayList.
If you're doing something else, then you're going to have to find a way to loop through the data . Once you get it into an array, the rest is pretty simple.
Is an ArrayList is just the interface for a dynamic array? Or are they the same thing?
like: ArrayList corresponds to dynamic array, HashMap corresponds to Map ?
except I don't see any Java API for something like a dynamic array, unless it is ArrayList?
Yes. In short. A longer explanation is that an ArrayList is a collection that uses arrays for storage, rather than a linked list, doubly linked list or similar. This means that it gives all the benefits of using an Array, whilst Java looks after the mechanics of sizing the Array for you (dynamically).
I seem to remember that the initial array is created with a default maximum size (which can be specified by the user). Should the collection run out of space, then a larger array is created and the contents of the original array copied into the new one. The increment in size is set to prevent this happening too often, as the operation is fairly costly.
Java also offers the Vector collection which is similar, but is also thread safe, see: What are the differences between ArrayList and Vector?.
ArrayList is the resizable-array implementation of the List interface.
So that's probably what you are looking for if you need a dynamic array.
ArrayList is not a dynamic array, it's not an array type dynamic or not, it's just one of the implementations of the List interface. Understand the difference between classes and interfaces. On the other hand arrays are container objects with the fixed size.
If in the dynamic sense you mean an array which can change in size then a List is an interface for a dynamic array. It is named ArrayList because it uses an array internally that's all.
Your analogy does not fit in the java collections framework since you can say that an ArrayList is a dynamic array but Map (or HashMap for that matter) does not have a "primitive" counterpart.
If by 'dynamic array' you mean an array in C++, then all arrays in Java are dynamic and stored on heap. ArrayList is a resizable wrapper for it. It also provides simple consistency checks - i.e. that you don't modify your array from outside during iteration.
What would be the best way to store and read a really long string, with each entry is an index for another array?
Right now I have this
String indices="1,4,6,19,22,54,....."
The string has up to hundred of thousand entries, so I think maybe I could use a data structure like Linked List. Does anyone know if it would be faster to use one?
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
you need to declare arraylist of type string.Then add to it.
It would depend on what you'll do with the string (the indices) and the corresponding arrays. Also, it will depend on how you're gonna access them.
I'd suggest you first read an overview about the data structures implemented in java, specially in the Collections Framework.
We could give some suggestions, but you'd have to provide us more information, specially those I mentioned in the beginning (what you want, how this data will be stored and accessed, and so on).
For example, if you need to have a fast access to the indexed data, maybe a string isn't even the best approach. Maybe a map would be better. The indexes could be the keys and the indexed arrays could be the values of the map, for example. But this is just a void example, I strongly suggest you give us more information.
I really like using the ArrayList class, which if your comfortable using arrays, ArrayList or any member of the Collections Framework. Would work really well. For what your trying to do.
ArrayList<String> indices = new ArrayList<String>();
indices.add("");
I have similar hunch in my mind , in which I want to like 1k number of strings and parse them (searching purpose to know it contain item or not).
Hence I found instead of using java collection framework - map or set or list
if I store data simply in array and start parsing data using for-loop, it is faster.
You visit this link and see actual output which we calculated in micro seconds.
https://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/
So using simple brute force is winner in case of unsorted array
(normally we have).
But arrays.BinarySearch() is winner if array is sorted.
I have this code:
newArray = new String[][]{{"Me","123"},{"You","321"},{"He","221"}};
And I want to do this dynamically.
Add more elements, things like it.
How do I do this?
PS: Without using Vector, just using String[][];
You can't change the size of an array. You have to create a new array and copy all content from the old array to the new array.
That's why it's much easier to use the java collection classes like ArrayList, HashSet, ...
You can't change the size of arrays. I think you have some options:
use a List<List<String>> to store a list of lists of strings
use a Map<String,String> if you're storing a key/value pair
Vector tends not to be used these days, btw. A Vector is synchronised on each method call, and thus there's a performance hit (negligible nowadays with modern VMs)
Java does not have the facility to resize arrays like some other languages.
But
You would not see a difference between a String array and a ArrayList<String> (javadoc) unless you are specifically required to do so (like in homework)
There are ways where you can declare a enormous array so that you dont run out of space but I would strongly recommend ArrayList for if you need dynamic changes to the size. And ArrayList provides some possibilities that are not (directly) possible with an array, as a bonus.
You can get away with using arrays if it's possible to calculate the size of arrays before using them. In your example, it seems that we need to know the size of the first array only. So you could impose some limit of how many records could be saved, or you could query user to know how many records it needs to save or something similar.
But again, it's easier to use Collections.
In Java, when would it be preferential to use a List rather than an Array?
I see the question as being the opposite-
When should you use an Array over a List?
Only you have a specific reason to do so (eg: Project Constraints, Memory Concerns (not really a good reason), etc.)
Lists are much easier to use (imo), and have much more functionality.
Note: You should also consider whether or not something like a Set, or another datastructure is a better fit than a List for what you are trying to do.
Each datastructure, and implmentation, has different pros/cons. Pick the ones that excel at the things that you need to do.
If you need get() to be O(1) for any item? Likely use an ArrayList, Need O(1) insert()? Possibly a Linked List. Need O(1) contains()? Possibly a Hashset.
TLDR: Each data structure is good at some things, and bad at others. Look at your objectives and choose the data structure that best fits the given problem.
Edit:
One thing not noted is that you're
better off declaring the variable as
its interface (i.e. List or Queue)
rather than its implementing class.
This way, you can change the
implementation at some later date
without changing anything else in the
code.
As an example:
List<String> myList = new ArrayList<String>();
vs
List<String> myList = new LinkedList<String>();
Note that myList is a List in both examples.
--R. Bemrose
Rules of thumb:
Use a List for reference types.
Use arrays for primitives.
If you have to deal with an API that is using arrays, it might be useful to use arrays. OTOH, it may be useful to enforce defensive copying with the type system by using Lists.
If you are doing a lot of List type operations on the sequence and it is not in a performance/memory critical section, then use List.
Low-level optimisations may use arrays. Expect nastiness with low-level optimisations.
Most people have answered it already.
There are almost no good reason to use an array instead of List. The main exception being the primitive array (like int[]). You cannot create a primitive list (must have List<Integer>).
The most important difference is that when using List you can decide what implementation will be used. The most obvious is to chose LinkedList or ArrayList.
I would like to point out in this answer that choosing the implementation gives you very fine grained control over the data that is simply not available to array:
You can prevent client from modifying your list by wrapping your list in a Collection.unmodifiableList
You can synchronize a list for multithreading using Collection.synchronizedList
You can create a fixed length queue with implementation of LinkedBlockingQueue
... etc
In any case, even if you don't want (now) any extra feature of the list. Just use an ArrayList and size it with the size of the array you would have created. It will use an Array in the back-end and the performance difference with a real array will be negligible. (except for primitive arrays)
Pretty much always prefer a list. Lists have much more functionality, particularly iterator support. You can convert a list to an array at any time with the toArray() method.
Always prefer lists.
Arrays when
Varargs for a method ( I guess you are forced to use Arrays here ).
When you want your collections to be covariant ( arrays of reference types are covariant ).
Performance critical code.
If you know how many things you'll be holding, you'll want an array. My screen is 1024x768, and a buffer of pixels for that isn't going to change in size ever during runtime.
If you know you'll need to access specific indexes (go get item #763!), use an array or array-backed list.
If you need to add or remove items from the group regularly, use a linked list.
In general, dealing with hardware, arrays, dealing with users, lists.
It depends on what kind of List.
It's better to use a LinkedList if you know you'll be inserting many elements in positions other than the end. LinkedList is not suitable for random access (getting the i'th element).
It's better to use an ArrayList if you don't know, in advance, how many elements there are going to be. The ArrayList correctly amortizes the cost of growing the backing array as you add more elements to it, and is suitable for random access once the elements are in place. An ArrayList can be efficiently sorted.
If you want the array of items to expand (i.e. if you don't know what the size of the list will be beforehand), a List will be beneficial. However, if you want performance, you would generally use an array.
In many cases the type of collection used is an implementation detail which shouldn't be exposed to the outside world. The more generic your returntype is the more flexibility you have changing the implementation afterwards.
Arrays (primitive type, ie. new int[10]) are not generic, you won't be able to change you implementation without an internal conversion or altering the client code. You might want to consider Iterable as a returntype.