adding unordered pairs without duplicates

B

bluedoze

Hello,

I want to construct a list of pairs without dupliactes, not the key
value pairs, I just want to ensure that the pair (not ordered) is not
dupliacted in the list.

for example

method input: (3, 4), (5, 6), (4, 3), (6, 5)

method output: (3, 4), (5, 6).

I can do this manually, but is there any utility in the java language
itself ?

Bluedoze
 
I

Ingo R. Homann

Hi bluedoze,

Hello,

I want to construct a list of pairs without dupliactes, not the key
value pairs, I just want to ensure that the pair (not ordered) is not
dupliacted in the list.

for example

method input: (3, 4), (5, 6), (4, 3), (6, 5)

method output: (3, 4), (5, 6).

I can do this manually, but is there any utility in the java language
itself ?

Bluedoze

I would use a normal (Hash)Set and a class "UnorderedPair" that
overrides equals and hashCode in the desired manner. Perhaps, it's
useful to store the two values as a "min" and a "max".

Hth,
Ingo
 
D

Daniel Dyer

Hello,

I want to construct a list of pairs without dupliactes, not the key
value pairs, I just want to ensure that the pair (not ordered) is not
dupliacted in the list.

for example

method input: (3, 4), (5, 6), (4, 3), (6, 5)

method output: (3, 4), (5, 6).

I can do this manually, but is there any utility in the java language
itself ?

If you use a collection that does not allow duplicates (such as a HashSet,
TreeSet or other Set implementation) then, given an appropriate
implementation of the equals() method (in your Pair class), any duplicates
will be discarded by the collection when you add them.

Beware, this is one of those situations where you really do need to
over-ride hashcode() when you override equals().

Dan.
 
B

bluedoze

it's actually not numbers, so I cannot use min and max.

any way thanks for the replies.
 
I

Ingo R. Homann

Hi,

it's actually not numbers, so I cannot use min and max.

any way thanks for the replies.

Well, it must not be numbers to use min and max. That's also possible
for Strings, for example, indeed for all classes that implement Comparable.

Even, if the 'values' do not implement Comparable, it should be possible
to write a proper Pair-class.

Ciao,
Ingo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top