0

I need to be using an implementation of Set interface for storing objects of type MyObject.

MyObject has two fields: id and score. For equality on MyObject, only id is used. One of the functionality I need to use is to be able to support to be able to add scores when two MyObjects (with same ids) are inserted into this set.

Currently, I am using TreeSet and its isn't working the way I want it to work.

    Set<MyObject> container = new TreeSet<MyObject>();
    MyObject obj1 = new MyObject(12, 0.345);
    container.add(obj1);

    MyObject obj2 = new MyObject(12, 0.1);
    container.add(obj2);

I want container to have Myobject(12,0.445) but it being a set, the container has MyObject(12, 0.1).

Is there something I can use which will give me what I am looking for?

3 Answers 3

1

You should use a Map for this:

Map<Integer, Double> container = new TreeMap<Integer, Double>();

or

Map<Integer, MyObject> container = new TreeMap<Integer, MyObject>();

Then you can call get on the container to see if the object is already there, and increment its score.

A Set will not work for you because there is no efficient way of getting the obj1 from the Set.

Sign up to request clarification or add additional context in comments.

Comments

0

Change the code/classes to follow the below semantics

if(container.contains(newObj))
{
  MyObject oriiginalObj = container.get(newObj);
  originalObj.incrementScore(newObj.getScore());
}

There are other ways of doing this like extending the TreeSet and overriding the add() method or by delegation (suggest using Guava's forwarding collection) but the solution I provided is simple and explicit.

Correction: Use TreeMap instead of TreeSet as suggested by Thomas

Comments

0

The add method for the TreeSet implementation looks like this

private transient SortedMap<E,Object> m; // The backing Map
public boolean add(E o) {
return m.put(o, PRESENT)==null;
}

where PRESENT is a dummy object used to indicate the object added already exists. you could subclass TreeSet to use the score sum instead of a dummy object

or, if possible, get rid of the Set altogether and instead use directly the Map as @Thomas says

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.