0

I've only used Comparators until now in order to sort in Array.sort(array,comparator).

I would like to impose order on a class that I am creating. Lets say I have a class Person and it has a lot of fields, for example I want to compare by first name.

I have a class that represents a PersonCollections. I would like to create an array list that self sorts itself in insertion. Lets say I have an ArrayList called people as a field and in insertion I would like to use a Comparator for example:

public void insert (Person p){
    for(int i = 0; i < people.size(); i++){
        if (people.get(i) > p){
            //Do something
        }
    }
} 

For now I have am implementing the Comparator interface and the compare method but it still doesn't recognize the > symbol on a Person class.

I would like to add that I am aware that by letting Person implements comparable I can get a good result but it is impotent for me to use Comparator here.

Thanks

NotSure
  • 651
  • 2
  • 7
  • 24
  • 1
    You want a "self-sorting" collection -- so don't use an ArrayList but rather a different collection that does this for you, such as a TreeSet. The only down side is that as a Set, it won't allow duplicates. – Hovercraft Full Of Eels Oct 29 '17 at 18:19
  • I am aware of that. I would like to impose this myself on an Array List. I have a specific requirement that insertion will be o(n) and removal will be o(1) which I think a self sorting array-list imposes. – NotSure Oct 29 '17 at 18:27
  • 1
    There is no such animal as a "self-sorting ArrayList". You can create a wrapper class and do your sorted insertions that way, but the ArrayList itself cannot be self-sorting. – Hovercraft Full Of Eels Oct 29 '17 at 18:28
  • Again, I am aware of that, this is exactly what I am trying to do. – NotSure Oct 29 '17 at 18:36
  • @NotSure Do not reinvent the wheel. If you want an automatically sorted collection of unique (no duplicates) `Person` objects, use: `SortedSet persons = new TreeSet<>() ;`. The `Person` objects will be returned to you in sorted order. – Basil Bourque Oct 29 '17 at 20:40
  • Hi guys, I appriciate the help and I understand all of this. I wish to specifically implement this using an arraylist. My question comes from curiosity and the desire to learn how to use comperators correctly. Please focus on my question with an understanding that this is a learning process and not the desire to write things as best as I can (time complexity/code complexity wise) – NotSure Oct 30 '17 at 09:31

0 Answers0