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 Overflow
🌐
Reddit
reddit.com › r/javahelp › when to use sets vs lists .
r/javahelp on Reddit: When to use Sets vs Lists .
July 31, 2022 -

I 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)?

🌐
Quora
quora.com › What-is-the-difference-between-Sets-and-Arrays-in-Java
What is the difference between Sets and Arrays in Java? - Quora
Answer (1 of 9): As mentioned before, a Set must not contain duplicate elements (which is allowed in arrays). This will (almost) always be true for a specific object with a specific address, so two members can never share the same memory address. This is however only a part of the truth. There ma...
Top answer
1 of 4
24

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.

2 of 4
3

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.

🌐
Reddit
reddit.com › r/learnjava › arraylist vs arrays?
r/learnjava on Reddit: ArrayList vs Arrays?
December 16, 2015 -

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?

🌐
GeeksforGeeks
geeksforgeeks.org › difference-between-a-set-and-an-array
Difference Between a Set and an Array
February 1, 2024 - Your All-in-One Learning Portal. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
🌐
Reddit
reddit.com › r/javahelp › set method for an array
r/javahelp on Reddit: set method for an array
November 19, 2022 -

i wonder how i could make a set method for an array

Top answer
1 of 4
3
Please be more specific about what you are trying to achieve. To change an array element at a given index you can simply use the assignment operator: array[index] = newValue
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
Find elsewhere
🌐
Medium
medium.com › @viranthrocky › understanding-the-difference-between-set-and-arraylist-in-java-4bac4b5214d9
🔍✨ Understanding the Difference Between Set and ArrayList in Java 🧠💻 | by Viranth Dharmalingam | Medium
April 11, 2025 - However, if an existing object shares the same hash code, Java uses the equals() method to check if the new object is truly equal to the existing one. If equals() returns true, the object is considered a duplicate and not added. If equals() returns false, the object is considered unique, and it is added, even though the hash codes match. This mechanism ensures that a Set never allows duplicate elements, unlike a List.
🌐
Reddit
reddit.com › r/java › can someone please explain to me when i would use array vs arraylist? using some real world example?
Can someone please explain to me when I would use Array vs ArrayList? Using some real world example? : r/java
July 17, 2016 - News, Technical discussions, research papers and assorted things of interest related to the Java programming language NO programming help, NO learning Java related questions, NO installing or downloading Java questions, NO JVM languages - Exclusively Java ... Archived post. New comments cannot be posted and votes cannot be cast. Share ... An array and a List are conceptually very similar: an ordered "bucket" of "things". Let's say you're creating an address book. You might have something like: public class Contact{ private String name; private Email email; private PhoneNumber phone; // getters and setters ...
🌐
Reddit
reddit.com › r/leetcode › array vs. hashset
Array vs. HashSet : r/leetcode
May 27, 2023 - A set is o(1) lookup but order is not maintained. An array is O(n) lookup so it would not be preferable.
🌐
Reddit
reddit.com › r/learnprogramming › the use of arrays v.s arraylists in java.
r/learnprogramming on Reddit: The use of Arrays v.s ArrayLists in Java.
May 31, 2012 -

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.

Top answer
1 of 3
9

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.

2 of 3
1

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.

🌐
Java67
java67.com › 2012 › 07 › difference-between-arraylist-hashset-in-java.html
Difference between ArrayList and HashSet in Java? Answer with Example | Java67
3. The differences between ArrayList and HashSet is that ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn't maintain any order.
🌐
Medium
paoladolcemascolo.medium.com › can-i-interest-you-in-a-set-the-set-vs-the-array-in-javascript-b410aad0ba9c
Can I interest you in a Set? The set vs. the array in Javascript | by Paola Dolcemascolo | Medium
March 12, 2021 - Another very important distinction between the two is that, while both Sets and Arrays are “collections”, a Set is considered a keyed collection, whereas an Array is considered an indexed collection.
🌐
Reddit
reddit.com › r/learnjava › lists vs arraylist vs arrays
r/learnjava on Reddit: Lists vs ArrayList vs Arrays
January 6, 2018 -

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.

Top answer
1 of 2
6

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.

2 of 2
1

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.

🌐
Medium
hanwenzhang123.medium.com › basic-data-structures-in-java-arrays-lists-sets-and-maps-7db29a7b1b82
Basic Data Structures in Java— Arrays, Lists, Sets, Stacks, Queues, and Maps | by Hanwen Zhang | Medium
November 13, 2022 - A list is like a shopping list, you can add the item you want at the end of the list, remove an item, or fetch an item from the list by getting its index. Unlike arrays, lists are empty when instantiated, you need to add the values in the list; otherwise, the list itself is empty upon creation. ... Sets have a slightly different purpose than lists.