Between Java and PHP – Arrays

Most PHP developers, that start learning Java face the same shocking issue – Java does not have arrays ! Well it is not completely true, Java has a notion of arrays, but not it the sense that most PHP developers are familiar to.

In PHP, the array is an universal container. It can be used as a map:

and as a list:

Could not embed GitHub Gist 2365239: API rate limit exceeded for 213.251.182.110. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

In PHP arrays are used everywhere, because they are very convenient. There are plenty of awesome functions that operate on arrays, to name just a few:

  • array_map
  • reduce
  • sorting functions
  • array_filter
The last cool feature of a PHP array is that, it remembers the order in which the elements where added.
In Java, things are slightly different. There are several collection types:
  • array – not actually a collection in Java sense, it has a fixed length (similar to SplFixedArray)
  • Map – a typed hash map (similar to PHP’s array, when we use string’s as keys), similar to SPLObjectStorage
  • List – a typed list – a container which remembers the order in which the items was added, similar to SPLDoublyLinkedList
  • Set – a typed collection of unique items

Every collection type is iterable (which means that you can use the for-each loop to iterate over it). All collection types derive from the base abstract Collection class.

The types that I have mentioned above are just interfaces, every one of it has different implementations which have some slightly different properties:

  • Map – implemented by HashMap and LinkedHashMap, the LinkedHashMap retains the insertion order
  • List – implemented by ArrayList and LinkedList, both implementations differ mainly in the speed of the operations – the ArrayList is faster for reading and the LinkedList is faster for writing
  • Set – implemented by HashSet, TreeSet and LinkedHashSet – the LinkedHashSet retains the insertion order, the TreeSet is sorted and the HashSet is the fastests

To even further complicate the notion of collections in Java, every collection type has it’s immutable form :).

To sum it all up, transitioning from PHP to Java in case of Arrays is not that difficult, you must just resolve which collection type you should use in each case. I will show some examples in the next post of this series, so stay tuned.

Leave a Reply

Notify me of followup comments via e-mail. You can also subscribe without commenting.