3

I've got a program that has a bunch of data objects. Each of these implement Comparable, and are set up to sort from highest to lowest (based on a simple long value) including duplicates values. I want these objects to be stored in a set/list such that I can iterate over it, and pull out each object in its respective place.

I've looked at using a TreeSet, however this does not allow duplicates, and so only keeps one of the many objects with the same values. I then found TreeMultiset, which could keep elements with the same value. The only problem with that is that it simply stores duplicates of the same object, rather than multiple objects that are equal.

Is there a library/built in object that I can use that will do what I want, or should I create an implementation myself?

Note: the reason I don't want the object duplicating in TreeMultiset is because the object contains a unique ID to a user, and a time value (this is what is compared)

ZephireNZ
  • 167
  • 1
  • 3
  • 7
  • possible duplicate of [Java: Sorted collection which allows duplicates, is memory efficient and provides fast insert + update](http://stackoverflow.com/questions/12827595/java-sorted-collection-which-allows-duplicates-is-memory-efficient-and-provide) – bumbumpaw Jul 09 '14 at 03:49
  • Alright, so I worked out how to solve my own question using the provided possible duplicate. In my case, I've simply used an ArrayList, with Collections.sort(). I chose this mainly because it kept the elements in order, and because it also allowed me to do ArrayList.subList(), which I had forgotten to mention was needed. – ZephireNZ Jul 09 '14 at 04:50
  • If you have two things, a unique id and a value associated to it, why not you think about TreeMap then? http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html – gprathour Jul 09 '14 at 05:26
  • Have you tried using `PriorityQueue` (it's an ordered data structure that allows duplicates). It implements `Iterable` thus, you can iterate it easily. Please note that it doesn't allow index based access though. – Daniel L. Jun 24 '16 at 14:33

1 Answers1

1

You can box to your same objects with a wrapper class such as:

class MyContainer:IComparable{
    public int compareValue;
    public List<object> data;

    public int CompareTo(MyContainer other){
        return this.compareValue - other.compareValue;
    }

    public void AddItem(object item){
        data.add(item);
    }

    public object GetItem(int Id){...}
}

class Program()
{
 TreeSet<MyContainer> data;
 public static void main(){
    data.AddToContainer("aaa");
    data.AddToContainer("aaa");
    data.AddToContainer("ccc");

 }

 public void AddToContainer(object item){
    if(data.contains(item)){
       data.get(item).AddItem(item);  
    }
    else{
       MyContainer cont = new MyContainer();
       cont.AddItem(item);
       data.add(cont);
    }
  }

}
eakgul
  • 3,658
  • 21
  • 33