As I go through interviews while looking for jobs, I often come home and revisit the questions as a learning experience. Here is an interview question that I often encounter: Given an array of integer where the elements (entries) are not sorted, write a function to return a new array with the duplicate entries removed. For example, if the original array is:
then the function should return:
The first time I tackled this problem, I did not make use of Java’s collections framework. As the result, the code are long, hard to read, and hard to maintain. When the interviewer asked me to improve the code, I finally thought of using the collections framework, but what kind of collection should I use? The interview was kind enough to provide me with a reference book for my research. To solve this problem, I need a collection that provides fast look-up, retains the original insertion order, and ignores the insertion of duplicate entries. As it turns out, Java collection framework does provide a collection that fit my demand and it is called LinkedHashSet. Using LinkedHashSet, I was able to simplify the code’s logic. For a complete listing of my code, follow the link here.