Depends on your data;
HashSet gives you an O(1) contains() method but doesn't preserve order.
ArrayList contains() is O(n) but you can control the order of the entries.
Array if you need to insert anything in between, worst case can be O(n), since you will have to move the data down and make room for the insertion. In Set, you can directly use SortedSet which too has O(n) too but with flexible operations.
I believe Set is more flexible.
Answer from JNL on Stack OverflowI acknowledge the difference between them on a basic level, like how sets don't allow duplicates and aren't in order, whereas lists have an order and allow duplicates, but from a performance standpoint, what are they better at doing? For example, if I have a group of integers that I want to store in no particular order, and contain no duplicates, will it always be better to store them in a set rathern than a list (with the exception of maybe a few very special cases)?
Say I need to do something like get a list of numbers from the user, so the user enters comma separated values and I get this input as a string, then pass it to a function that parses this input. The way I would do it is to return it as an ArrayList, not an array. Is this the "right" way to do it?
Depends on your data;
HashSet gives you an O(1) contains() method but doesn't preserve order.
ArrayList contains() is O(n) but you can control the order of the entries.
Array if you need to insert anything in between, worst case can be O(n), since you will have to move the data down and make room for the insertion. In Set, you can directly use SortedSet which too has O(n) too but with flexible operations.
I believe Set is more flexible.
The choice greatly depends on what do you want to do with it.
If it is what mentioned in your question:
I have a collection of objects that are guaranteed to be distinct (in particular, indexed by a unique integer ID). I also know exactly how many of them there are
If this is what you need to do, the you need neither of them. There is a size() method in Collection for which you can get the size of it, which mean how many of them there are in the collection.
If what you mean for "collection of object" is not really a collection, and you need to choose a type of collection to store your objects for further processing, then you need to know, for different kind of collections, there are different capabilities and characteristic.
First, I believe to have a fair comparison, you should consider using ArrayList instead Array, for which you don't need to deal with the reallocation.
Then it become the choice of ArrayList vs HashSet, which is quite straight-forward:
Do you need a List or Set? They are for different purpose: Lists provide you indexed access, and iteration is in order of index. While Sets are mainly for you to keep a distinct set of data, and given its nature, you won't have indexed access.
After you made your decision of List or Set to use, then it is a choice of List/Set implementation, normally for Lists, you choose from ArrayList and LinkedList, while for Sets, you choose between HashSet and TreeSet.
All the choice depends on what you would want to do with that collection of data. They performs differently on different action.
For example, an indexed access in ArrayList is O(1), in HashSet (though not meaningful) is O(n), (just for your interest, in LinkedList is O(n), in TreeSet is O(nlogn) )
For adding new element, both ArrayList and HashSet is O(1) operation. Inserting in the middle is O(n) for ArrayList, while it doesn't make sense in HashSet. Both will suffer from reallocation, and both of them need O(n) for the reallocation (HashSet is normally slower in reallocation, because it involve calculation of hash for each element again).
To find if certain element exists in the collection, ArrayList is O(n) and HashSet is O(1).
There are still lots of operations you can do, so it is quite meaningless to discuss for performance without knowing what you want to do.
Hey! I am currently going through the http://mooc.cs.helsinki.fi/ tutorial to learn Java, and it is great so far! I seem to pick up things quite easily. But there is one thing I don't really understand, mainly because I am missing some context I think. But why do we make arrays holding String values like so?
ArrayList<String> varName = new ArrayList<String>();
varName.add("title1");
instead of just:
String[] varName = { "title1", "text2" };
since both seem to work just fine? Or do I use both syntaxes at different times?
A simple array is not dynamic, meaning that you only get two spots in the array where as the array list will expand as needed. In your example the array would error if you added a third string while in the list you can add strings effectively infinitely (not LITERALLY true but true enough for practical purposes). Now why would you want to use the simple array because it's less overhead and faster. With the array list you want to pass the size you think it will be to the constructor if you can, because basically the way the array list works is when it hits its size limit it makes a new array list that's double the length and copies the old contents into it, so the fewer times you have to do that the better.
ArrayLists are different from arrays in the two ways:
-
ArrayLists can change in memory length, meaning you can add stuff to them later without the compiler giving you an error.
-
ArrayLists can also hold class objects. I don't know if you've gotten to classes in your tutorial yet, but this is a big deal.
i wonder how i could make a set method for an array
In java, what is the difference between a hash set and an arraylist, and in what kind of situation would you choose a hashset?
Major container types provided in most languages are lists, maps and sets. I was thinking sets seem more specific and have much less use cases than other two. Can what I said be shown statistically somehow? Is my assumption correct?
By real programming, I meant programming excluding educational and competitive.
I am an intermediate level programmer (non-professional) and there is something I have been wondering. What is the purpose of an array vs and array list? When would you use on over another? Surely an ArrayList is more convinient, as you do not need to say the specific index to put the data in by using x.add(y)? Any explaination would be greatly appreciated.
Arrays and ArrayLists are both used for the same thing (storing more than one object), but are used in different places.
The main difference between the two is that ArrayLists can "grow" but arrays can't. That is to say, when I make a new array, I have to tell Java how big it is. Like so:
int[] bunchOfNumbers = new int[50];
This makes an array that can hold 50 integers.
However, if we were to do this with an arraylist, we don't have to tell it how big to go, so we can just write :
ArrayList<Integer> bunchOfNumbers = new ArrayList<Integer>();
So, what do these differences mean?
Well, for one thing, we can't add any more than 50 numbers to our array. On the other hand, we can add as many numbers to the ArrayList as we damn well please.
The downside to ArrayLists is hard to understand without knowing how ArrayLists work, so I'll do that first.
An ArrayList is, at its core, an array. However, because a standard Array can't grow, it needs to pay attention to if you are going to over-extend. If you are, it creates a new bigger array, copies over the elements in the old array, and then adds your new value to it.
Now we can understand that adding things to an ArrayList can take time because we have to copy the previous array when it has to grow.
So, to conclude
Array
-
Very fast
-
Can't grow past their initial limit.
ArrayList
-
Can be slower
-
Can grow very large on demand
If you have any questions, feel free to ask. There are also other Lists in java that might be of use to you like the LinkedList, which has very fast insertion and deletion but is slow if you need to pull a specific element out of it.
Use an array when you know exactly what size it's going to be and it won't change,
an ArrayList when you don't,
and a LinkedList if you plan on inserting and removing a lot.
The only real benefit I see to array is that it is slightly faster to get and set elements. However, arraylist seems much more simple if you want to add, remove, elements and the set/get methods are only slightly longer to implement. So from this it seems as if arraylist is much more superior. Why would you use an array over arraylist then?
List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered (thank you, Quinn Taylor).
List<E>:
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Set<E>:
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
| List | Set | |
|---|---|---|
| Duplicates | Yes | No |
| Order | Ordered | Depends on implementation |
| Position Access | Yes | No |
Map implementation:
public final class Person
{
... remainder left to the student ...
}
Map<Person, Date> currentPartyAttendees; // date is arrival time.
Set implementation:
public final class PartyAttendee
{
... person details ...
Date arrive;
int hashcode()
{
... use Apache HashCodeBuilder ...
}
boolean equals(Object other)
{
... implementation left to student. Use Apache EqualsBuilder ...
}
}
Set<PartyAttendee> currentPartyAttendees;
Using a HasMap would suit your purpose, as you can use the person's name as a key to add and retrieve the entry for the person, and it offers constant time performance, so regardless of how large the set grows, the performance should remain consistent.
As a beginner just getting into java, I feel very comfortable with arrays; I’ve already built multiple programs using arrays.
That being said, I’ve recently discovered the List and ArrayList functions and I’m wondering how they differ from Arrays, how they may be similar to Arrays, and in what situations I would use Lists or ArrayLists as opposed to just an array.
Also, is it bad relying on Arrays to do a lot of programs? For example, I’ve used Arrays to find minimum values of pairs, when I could’ve just used GetMin function instead. Are there any downsides to using Arrays?
Thanks in advance.
this is a nice example of why it's helpful to know data structures. it's not to solve leetcode problems, it's to know when to use what. so you know what an array is, you declare an array size and you can access elements with O(1) run time, but if you want to reorder things, you have to shift all the elements downstream, which takes more time.
"List" in Java is just in interface, you have to specify what type of list you want to use. There are several list types to choose from, most commonly a LinkedList or ArrayList. An interface is just a set of Methods, so whatever list type you create will have those methods to choose from, but they may be implemented differently behind the scenes.
An ArrayList in Java is maybe somewhat misleadingly named. It's just a dynamically sized array that has the Methods of a list. You don't have to declare a size for an ArrayList. It will automatically allocate a size for you, without telling you because you don't care, and if you reach the limit of the allocated size it'll add some more size for you without you needing to do anything. I think it creates a new, bigger array to do this, but I'm not 100% sure. So, use an ArrayList when you want the O(1) access run time of an array, but the size of the array is unknown or changing. If you're familiar with Python, what Python calls a List is essentially the same thing as what Java calls an ArrayList.
The general rule is that if you know or can calculate the needed size of a collection, you would use an array.
Not really. Even if you know the size up front you can use an arraylist just fine. It's backed by an array after all and you have all the conveniences of the collections (streams, copying, etc.) and all the different API/library methods that take lists but not arrays. Just mentioning this so beginners don't get the impression they should use arrays if they know the size up front.
Think of lists as the "backup option" when you can't use an array because you don't know what size you need the array to be.
So no; lists are not a 'backup option' at all. The collections are the primary collections you'll be using. Using 'just' arrays are something you very rarely see in code, even where you know the size up front or the list is hard-coded.