-3

Recently I've been making Bukkit Minecraft plugins in Eclipse for a project and I've been using an arraylist to store the player objects. After some messing around trying to optimise my code, I realised that there is another way to define said List of objects using a java Collection. Now I have the basics down which is that a collection, unlike an arraylist, does not allow you to reference a variable based on the index but I'm not using that in my code so I was wondering if there are any other advantages regarding CPU or memory usage? Note* I do know that by passing the variable around as a Collection it's easier to cast it to other forms of lists but I'm confident I won't be doing this in my code so I wouldn't be regarding this as an advantage.

1615903
  • 32,635
  • 12
  • 70
  • 99
  • 2
    `ArrayList` is one of the most efficient collection in terms of memory usage (it's essentially an array of references) - I'm not sure what you expect to gain in that respect when switching to something else. – assylias Nov 06 '17 at 09:51
  • This whole question is based on a fundamental misunderstanding. `Collection` is an interface not a class, and that makes questions about CPU & memory performance of `Collection` meaningless. I recommend that you take the time to read a Java tutorial or a Java textbook. It will save you time in the long run. – Stephen C Nov 06 '17 at 10:39

1 Answers1

2

Collection isn't a class, it's an interface. That is, it doesn't actually do anything; it just defines which methods are available. In fact, ArrayList supports the Collection interface. So, you can do this:

ArrayList<Integer> list = new ArrayList<>();

But you can do the following, and they are functionally identical:

Collection<Integer> list = new ArrayList<>();

However, in the latter example, because you are now referencing the ArrayList as a Collection, you only have access to the the methods on Collection, which, as you have discovered, is a lot more restricted than ArrayList.

ArrayList also supports the List interface, which itself extends Collection, and provides the additional list methods, so you can do this (and this is generally recommended):

List<Integer> list = new ArrayList<>();

So the performance of Collection vs ArrayList isn't really a valid question. What I think you want to know is the comparative performance of different List implementations. The main single-threaded implementations in Java are ArrayList and LinkedList. These are created like this:

List<Integer> arrayList = new ArrayList<>();
List<Integer> linkedList = new LinkedList<>();

You will find plenty of materials out there with the pros and cons of each. For example: When to use LinkedList over ArrayList?

Graham
  • 169
  • 6