我正在尋找一些實現Collection接口的地方,我可以添加同一對象的多個實例(基於給定的比較器),但該集合不能包含兩次相同的對象標識(基於==運算符)。集合必須進行排序,我必須能夠刪除一個特定的元素(基於==運算符)。一個有多個實例但唯一對象標識的排序集合
換句話說,它必須滿足以下測試用例:
public MyCollection<E> implements Collection<E>
{ ... }
public class MyCollectionTest extends TestCase
{
static class MyComparator implements Comparator<MyInterface>
{
@Override
public int compare(MyInterface pO1, MyInterface pO2)
{
// the return type of getCategory() is just an enum.
return pO1.getCategory().ordinal() - pO2.getCategory().ordinal();
}
}
public void testAdd()
{
MyCollection<MyInterface> sut = new MyCollection<MyInterface>(new MyComparator());
MyInterface svc1 = EasyMock.createNiceMock(MyInterface.class);
MyInterface svc2 = EasyMock.createNiceMock(MyInterface.class);
EasyMock.expect(svc1.getCategory()).andStubReturn(Category.CAR);
EasyMock.expect(svc2.getCategory()).andStubReturn(Category.VAN);
EasyMock.replay(svc1, svc2);
sut.add(svc1);
sut.add(svc2);
assertEquals(2, sut.size());
assertSame(svc1, sut.last());
assertSame(svc2, sut.first());
}
public void testAddDouble()
{
MyCollection<MyInterface> sut = new MyCollection<MyInterface>(new MyComparator());
MyInterface svc1 = EasyMock.createNiceMock(MyInterface.class);
EasyMock.expect(svc1.getCategory()).andStubReturn(Category.CAR);
sut.add(svc1);
sut.add(svc1);
assertEquals(1, sut.size());
}
public void testRemove()
{
MyCollection<MyInterface> sut = new MyCollection<MyInterface>(new MyComparator());
MyInterface svc1 = EasyMock.createNiceMock(MyInterface.class);
MyInterface svc2 = EasyMock.createNiceMock(MyInterface.class);
EasyMock.expect(svc1.getCategory()).andStubReturn(Category.VAN);
EasyMock.expect(svc2.getCategory()).andStubReturn(Category.VAN);
EasyMock.replay(svc1, svc2);
sut.add(svc1);
sut.add(svc2);
assertEquals(2, sut.size());
sut.remove(svc1);
assertEquals(1, sut.size());
}
}
任何幫助嗎?
謝謝!
謝謝。ForwardingMultiSet來自谷歌收藏,不是嗎?我目前不依賴他們,但它可以作爲一種選擇。但是,快速查看API,我看不出如何根據其身份移除對象。 – PeeWee2201
謝謝,我可以通過我的所有測試用例與您的IdentityTreeSet!做得好! – PeeWee2201
爲了保持一致性,您可能需要重寫contains以使其基於身份。 – MikeFHay