开发者

Java: List insert of more than one object with same HASH

开发者 https://www.devze.com 2023-04-08 18:54 出处:网络
I\'m having a bit of trouble with this one: I need to override the hashCode() and equals(), resulting in some objects being \"equal\". That\'s the intended behavior, but i have collateral problems wi

I'm having a bit of trouble with this one:

I need to override the hashCode() and equals(), resulting in some objects being "equal". That's the intended behavior, but i have collateral problems with collections (has expected...):

I work with an ArrayList, and inserting a duplicate object at a predefined index is not honored by the insert method. Instead it is inserted at the PREVIOUS position of the FIRST duplicated existing element.

Let's say i have
A
B
C

And i insert duplicate of A at index >0...

it will be inserted at index 0.
->A
A
B
C

Is this normal behavior?

Thanks.

EDIT: Object is inserted at right position. The TableViewer i'm using (org.eclipse.jface.viewers.TableViewer) was confusing me, because it defaults the edit t开发者_运维知识库o the FIRST duplicated element (and that makes some sense...).


I think in the list it does not matter whether it's duplicate or not.

I think it depends whether we are doing (as to where they will end up in the list) -

list.add(obj);
//or
list.add(index, obj);
//or
list.set(index, obj);

Other than that for a List, it's the order in which we add the object to the list.

Because if we have list like

List list = ArrayList();

Than it doesn't matter what type of object we add into it, so it does not make any difference whether we have the hashCode and equals defined or not.


no that isn't normal.

as far as i know, no implementation of java.util.List uses the equals() or hasCode() method

can you provide some code sniped please?

Maby you were looking at the first A you have prevously inserted?

A // prevously inserted 
B 
C 
A // the new duplicat
0

精彩评论

暂无评论...
验证码 换一张
取 消