我有一个名为脚本的Set。 E类具有id,squence等元素。我想在脚本中比较两行对象E,并仅在id和sequence相同时删除。我该怎么做。我有一个删除所有行的代码。任何人都可以更正此代码以仅删除具有相同ID和序列的代码。
LinkedList<EditorScriptRow> lList = new LinkedList<EditorScriptRow> (_scriptRows);
for (ListIterator<EditorScriptRow> i = lList.listIterator(); i.hasNext();) {
EditorScriptRow row = i.next();
int k =0;
for (ListIterator<EditorScriptRow> j = lList.listIterator(k+1) j.hasNext();) {
EditorScriptRow row1 = j.next();
if ((row.getTemplateRow().getId() != null) &&
(row.getSequence() != null) &&
(row.getEdit().getName() != null) ) {
if ((row.getSequence().equals(row1.getSequence())) &&
(row.getTemplateRow().getId().equals(row1.getTemplateRow ().getId ())) &&
(row.getEdit().getName().equals(row1.getEdit().getName()))) {
_scriptRows.remove(row);
}
}
}
k++;
}
答案 0 :(得分:2)
您提到“Set”但您的代码使用LinkedList。它是哪一个?
您是否可以访问EditorScriptRow类的源代码?
如果这样做,您可以覆盖equals方法。 Set接口的合同是它可能不包含两个被“equals”方法认为相等的对象。因此,您可以使用Set的实现(例如HashSet),这样,您只需将对象添加到Set中,就可以保证没有重复的项目。
答案 1 :(得分:1)
我会编译一个id +序列列表并检查它。我刚刚潦草地写了这个,所以它可能需要一些改进但是类似......
Set idSequence = new HashSet();
for ( Iterator iterator = list.iterator(); iterator.hasNext(); )
{
EditorScriptRow row = (EditorScriptRow) iterator.next();
if ( ( row.getTemplateRow().getId() != null )
&& ( row.getSequence() != null )
&& ( row.getEdit().getName() != null ) )
{
String idAndSequence = row.getTemplateRow().getId() + row.getSequence();
if ( idSequence.contains( idAndSequence ) )
{
iterator.remove();
}
else
{
idSequence.add( idAndSequence );
}
}
}
答案 2 :(得分:0)
您可以在迭代器上使用remove()来删除next()返回的最后一个元素。
答案 3 :(得分:0)
在EditorScriptRow中覆盖等于
@Override
public boolean equals(Object o) {
if (o instanceof EditorScriptRow) {
EditorScriptRow other = (EditorScriptRow) o;
return this.id.equals(other.id) && this.sequence.equals(other.sequence);
}
return false;
}
然后创建一个Set而不是链表。
Set<EditorScriptRow> set = new HashSet<EditorScriptRow>();
当您将EditorScriptRow对象添加到集合时,将忽略重复项,因为您以这种方式覆盖等于
如果没有意义http://java.sun.com/docs/books/tutorial/collections/index.html
,您可能希望查看一些Java集合教程