0

C++

Say we insert 5 objects into a set.Each object has a id and a name as the attributes.We can get an iterator to the element we are searching for by say

int main()
{
   set<Obj*> setObj;
   Obj *objA = new Obj(10,"P"); Obj * objB = new Obj(20,"L");
   setObj.insert(objA);setObj.insert(objB);
   set<Obj*>::iterator it = setObj.find(objA);
   if( it > 0 )
       it->name = "New name";
}

//Hope the idea is clear.I basically can change the non key part of the object in the set .in this case the obj class has key as id

Now in Java since we dont have set offering find, is the only way to do so is by looping through?

apologies if the syntax is not exactly right.Havent compiled the code

Abhishek
  • 151
  • 1
  • 1
  • 9
  • Yes you'll have to loop through it by calling the `iterator()`. http://stackoverflow.com/questions/7283338/getting-an-element-from-a-set – user2336315 Jan 05 '14 at 07:42
  • 6
    The above code doesn't do in C++ what you think it does: the code use a `std::set` ordered by the pointer values. If you wanted to have the objects sorted by their `id` you'd need to use a custom comparison object. Also, you can't compare iterators to `0` you need to compare the iterator against the `end()` of the set. – Dietmar Kühl Jan 05 '14 at 07:50
  • please, start adding spaces next to dots at the end of sentences... – V-X Jan 05 '14 at 08:06
  • Yes the object class has the < operator overloaded to compare using id and ok we compare against the end..but then still we cant do something similar in java? – Abhishek Jan 05 '14 at 08:08
  • You probably should be using a `std::map` anyway - you want to map the immutable key to a mutable (though the keyword is not needed) value. This self-documents what you're trying to do automatically. This also makes your goal easier to achieve, provides compiler safety (via the type system), and in C++, eliminates the need to allocate your objects on the heap before passing them in (which is always a win). Java's Map interface also has a [get method](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#get(java.lang.Object)), which should let you do what you need. – Mark Jan 05 '14 at 08:49

2 Answers2

1

A set in Java is for unique, immutable elements.

If you want to have changeable values associated with a key, you should use a Map. BTW Most Set implementations just wrap a Map.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
-1

Java Set doesn't hava search method.It only has contains(Object o) and containAll(Collectiono) method. You have to iterate the set because Java set is unsequenced.The index is nonsense.

Dylan
  • 16
  • 1
  • 3