When to ArrayList - java

Very much a beginner question here, but hopefully a pertinent one.
I've been attempting to teach myself Java by way of coding a crappy little roguelike.
Since I discovered the collections framework, I've found that I'm using arraylists absolutely everywhere - so much so in fact that I find myself worrying I’m being woefully inefficient by using them in places where a regular array would suffice.
Thus my question is this: Under what circumstances should I favour using an arrayList over a regular array (or vice-versa) and why? Is there some kind of simple rule of thumb to help me pick which I should be using for any given task?
I refute that this duplicates Array or List in Java. Which is faster? - my question asks in which situation one is more methodologically sound than the other, and not which is generally quicker for any given task.

As said in Effective Java, one should prefer Lists to arrays.
One of the major differences is that arrays are covariant by their type and thus need accurate handling. Also, their type is reified and they do not mix well with generics.
But the implication is that arrays are able to work with primitives while generic collections aren't: they have Objects inside. So you might prefer arrays in performance critical parts of your code to avoid primitives boxing-unboxing.

If you know that your collection will always be a fixed length then use array.
If your collection is variable in length, I.e it could hold 1,5,100 values then use arraylist.
Example.
An application that asks the user a series of questions, the user can try get the answer right as many times as they like.
You create an array of possible answers to a question, you know there will only ever be 5 possible answers for each question, you would use an array of length 5 to store the possible answers.
You decide to create an array of all the answers the user submits, they could submit any number of answers, you'd store these in an arraylist as the user could give 1 or 100 answers before getting the question correct, a fixed length array here wouldn't do the job.
Hope that helps

Related

Array vs ArrayList: Dynamic Use

Both ArrayLists and Vectors make use of typical arrays internally. However, that leaves me thinking... why would I use ArrayLists when I can technically do the same thing using Arrays? Is convenience the only reason? Do performance-critical applications ever make use of an ArrayList?
Any tips would be appreciated.
I believe there are multiple reasons to prefer Lists over "implementing lists over arrays" or over "using arrays", but here are the two that I think are most important:
Lists have better support to generics than Arrays (you can, and should, read about it in "Effective Java" by Bloch - see Item 25)
If you ask about using ArrayList vs. implementing it yourself - I find it hard to believe that you'll do a better job than the guys that developed it in openjdk (Josh Bloch and Neal Gafter).
Yes, performance critical applications use ArrayList all the time. It's very unlikely that array access is the dominant factor in the vast majority of programs written in Java.
The ArrayList Collection interface is much richer than the functionality provided by built-in primitive arrays. This extra functionality will save you development time as well as debugging time by not having to write those algorithms yourself.
Additionally, many programmers are already familiar with the ArrayList Collection interface and thus by utilizing the existing standard libraries it will make your code easier to read and maintain for the long term.
One reason is that ArrayLists sizes are dynamic, arrays aren't.
The internal implementation of ArrayList is array only. but ArrayList is an wrapper class which is having more capabilities added to it. These capabilities are not available when you deal with Array directly.
For example,
Delete an element from array, you will have to implement logic if your are using an Array. But if you are using ArrayList, it will do the deletion for you.
Adding an element to array:
If you are using an array, you will have to implement the logic. But using an ArrayList, it is pretty easy.
You will find lot of methods in this ArrayList class that are handy for day to day use.
Hope this will help you.

Is it possible to create a grid reference system for strings to be referenced by variables?

Essentially, what I am trying to do is create a system that will take two inputs that references a row and a column of a grid, returning the value for that point. I am a very novice Java programmer, having moved to Java from Raptor. I know what I am looking to do with a long strand of if statements, however I want to avoid that. Essentially having an input refer to one of three columns, and another input refer to one of three rows, and the output being the point between them. I'm sorry for the lack of any coding, however I have no idea how I would even code it to begin with.
You can use a 2 dimensional array, or hashmaps.
Syntax for creating a two-dimensional array
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
http://www.tutorialspoint.com/java/java_hashmap_class.htm
Questions to ask yourself:
How many values? What operations are priority?
If the value set is small, and the time constraints on access are minor, then you can use either without any concerns.
The hash map memory footprint will be heavier, but you can use more complicated (arbitrary) keys.
Memory overhead of Java HashMap compared to ArrayList
For simplicity I would probably use the 2d array approach if it more closely models the structures you're creating.

Java syntax scenario where Collection<Foo>[] is necessary and/or valid

I came across an interesting piece of code while learning morphadorner manipulations. The code is below:
Collection<Object>[] nodes = someFunction()
My question is in what scenario is this declaration necessary and/or valid:
Collection<Object>[] nodes
I have seen:
Collection<Object[]> nodes
But cannot think of a scenario where I would need an Array of Collections. So again the question is, when would this be used?
This is the javadoc:
java.util.Set<java.lang.String>[]
findNames(java.lang.String text)
Returns names from text.
First of all,
Collection<Object[]> nodes;
and
Collection<Object>[] nodes;
are two different things. The first is a collection of arrays, whereas the second is an array of collections.
As to when you'd use the latter, my answer would be "rarely". While conceptually this is pretty simple, Java arrays and generics don't play together nicely.
It is therefore more common to see
ArrayList<Collection<Object>> nodes;
which is similar but much easier to deal with.
As to whether findNames() is an example of good design, my main objection is that it's completely impossible to guess from the function signature what the elements of the array are supposed to represent (or how many there are). For this reason, I would have done it differently, probably returning a custom class with two clearly-named accessors.
The code compiles, so it's probably valid Java.
It's necessary when the designer couldn't think of a better solution.
Which leaves us with: Is it good design?
Maybe but probably not. One scenario would be if the function always returns two or three collections (i.e. more than one but the number never changes).
You could create an object for this but since this is Java, this would take many, many, many lines of deadly boring code. It would also mean that you would have to come up with some useful names for each collection.
Taking the JavaDoc into account that you posted, it seems the number of arrays depends on the number of sentences in the text.
So in this scenario, I would return a List of Collections (since the order of sentences never changes and you might want to get them by index).
The designer might argue that you can add elements to a list but not to an array but I'd use an unmodifiable list.
So in this example, I'd say it's bad design.
Collection<Object>[] nodes
is Valid because it means that we are getting an array of Collection<Object> .
Whereas,
Collection<Object[]> nodes
means we are getting a Collection that contains arrays of Objects.
My question is in what scenario is this declaration necessary and/or
valid:
Consider the situation when you have different set of objects say (people). Each set belong to the people of particular country. And we create an array of set of specified size. In that case we use the following syntax:
Set<People>[] setOfPeople = new TreeSet<People>[5]; // We want to consider people of 5 different countries.

Java - List or Array? [duplicate]

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
When to use a List over an Array in Java?
(9 answers)
Closed 9 years ago.
I know Lists make things much easier in Java instead of working with hard-set arrays (lists allow you to add/remove elements at will and they automagically resize, etc).
I've read some stuff suggesting that array's should be avoided in java whenever possible since they are not flexible at all (and sometimes can impose weird limitations, such as if you don't know the size an array needs to be, etc).
Is this "good practice" to stop using arrays at all and use only List logic instead? I'm sure the List type consumes more memory than an array and thus have higher overhead, but is this significant? Most Lists would be GC'ed during runtime if they are left laying around anyways so maybe it isn't as big of a deal as I'm thinking?
I don't like dogma. Know the rules; know when to break the rules.
"Never" is too strong, especially when it comes to software.
Arrays and Lists are both potential targets for the GC, so that's a wash.
Yes, you have to know the size of an array before you start. For the cases when you do, there's nothing wrong with it.
It's easy to go back and forth as needed using java.util.Collections and java.util.Arrays classes.
I think a good rule of thumb would be to use Lists unless you NEED an Array (for memory/performance reasons). Otherwise Lists are typically easier to maintain and thus less likely to cause future bugs.
Lists provide more flexibility/functionality in terms of auto-expansion, so unless you are either pressed for memory (and can't afford the overhead that Lists create) or do not mind maintaining the Array size as it expands/shrinks, I would recommend Lists.
Try not to micromanage the code too much, and instead focus on more discernible and readable components.
It depends on the list. A LinkedList probably takes up space only as it's needed, while an ArrayList typically greatly increases its space whenever its capacity is reached. Internally, an ArrayList is implemented using an array, but it's an array that's always larger than what you want. However, since it stores references, not objects, the memory overhead is negligible in most cases and the convenience is worth it, I believe.
I would have to say I follow this approach of using the Collections framework where I might otherwise have used an array. The collections offer you many benefits and convenience over arrays but yes there is likely to be some performance hit.
It is better to write code that is easy to understand and hard to break, arrays require you to put in a lot of checking code to ensure you don't access bits of the array you shouldn't or put to many things in it etc. Given that the majority of the time performance is not a problem it shouldn't be a concern.

Why exactly are Java arrays not expansible? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why aren’t arrays expandable?
I am starting to learn Java as my Computer Science school's assignments require this language and I'm liking the language. However, I've seen that Java arrays are not expansible - that is - you must declare their length before using them and it can't be changed further.
I'd like to know exactly why is that? Why the Java language designers chose to to make arrays as such? I guess it's for performance concerns but I'm not sure.
Thanks everyone in advance.
I'd like to know exactly why is that? Why the Java language designers chose to to make arrays as such? I guess it's for performance concerns but I'm not sure.
They designed primitives and arrays to be as simple and low level as possible. They don't do anything special and arrays don't use Object Orientated design at all. i.e. they only have a few useful methods, none specific to arrays.
The idea was that you would write higher level collections such as Lists using these low level constructs.
Java arrays are almost as simple as C arrays. C array is just a allocated memory region of n*m bytes where n is the number of elements in the array and m is the number of bytes needed to store a single element.
Then only thing Java added here is length and probably toString(). All other features can make array performance ineffective. Collections do that very well. Moreover collections are written in java itself that makes them portable.
Why the Java language designers chose to to make arrays as such?
Arrays are one of the programming data structures provided by the language. if you make Array also expandible, it'll become similar to ArrayList.
So, i guess because of two reasons:
To make Java similar to previous languages on basic constructs.
To remove duplication.
Arrays occupy consecutive memory locations and the compiler cannot make sure that the locations following the end of the array are available to be added to the array.
That is why many people Use LinkedList or ArrayList
This question is answred
Why aren't arrays expandable?

Categories