• Register

Let’s start with a general approach of these two.

ArrayLists and TreeSets are both part of a big family known as Data Structures or DS, and as the name explains itself, Data Structures present a format to store data and/or manage it efficiently, and if used adequately could save lots of execution time as each DS present a different way to access the data.

Now let’s start with their application in Java.

  • In term of popularity, ArrayList wins here.

Data in ArrayLists is stored based on an index and is independent of the natural order of that Data. Which means an ArrayList of integers could have the number “10” stored in index 0, the number “4” stored in index 1 and the number “6” in index 2 of that list.

When it comes to TreeSet, the data is stored based on its natural order, which means No duplicate records are allowed, and if a new Data Type is to be stored, the relative class should implement the “compareTo” method so that the TreeSet could know according to which order it should present the Data.

  • From a sorting point of view, TreeSet takes the edge here.

The presentation of the popularity above shows us a clear difference between the two when it comes to sorting.

Data in ArrayLists are independent from each other, which is clearly less efficient in a searching and/or deleting action than in a TreeSet.

As we already stated before, in a TreeSet, each new element gets automatically stored in its relevant place according to the order entered in the Class of the new Data Type, or from the natural order indicated with the good old Primitive types, which makes it less time consuming to find it and manipulate it.

Finally, which of the two DS should you use to organize your Data?

Well as simple as it may seem, it depends on the tasks that you will be executing on your collection.

ArrayList mainly promotes random data access, values duplication, and simplicity.

Whereas TreeSet is used to enter a bulk of data, order it, and then store it in a set which facilitates the search of a specific element.

100 points