[英]Creating list of unique objects
我通過解析html文檔得到了一組元素。 元素可能包含重復項。 僅列出唯一元素的最佳方法是什么?
我來自C ++背景,看到使用設置和自定義相等操作完成此操作的可能性。 但是,不確定如何用Java做到這一點。 感謝任何可以幫助我以正確,高效的方式進行操作的代碼。
ArrayList<Element> values = new ArrayList<Element>();
// Parse the html and get the document
Document doc = Jsoup.parse(htmlDataInStringFormat);
// Go through each selector and find all matching elements
for ( String selector: selectors ) {
//Find elements matching this selector
Elements elements = doc.select(selector);
//If there are no matching elements, proceed to next selector
if ( 0 == elements.size() ) continue;
for (Element elem: elements ){
values.add(elem);
}
}
if ( elements.size() > 0 ) {
????? // Need to remove duplicates here
}
java.util.HashSet
將為您提供無序集,API中還有java.util.Set
其他擴展,如果需要,它們將為您提供有序集或並發行為。
根據Element類的不同,您可能還需要在其上實現equals和hashCode函數。 根據@musical_coder的評論。
例如:
Set<Element> set = new HashSet<Element>(elements);
為了提供一個覆蓋的equals方法或Element,我將為我自己的MyElement或更明智地命名的東西(例如)圍繞Element類創建一個薄包裝器。
public static class MyElement extends Element {
private final Element element;
public MyElement(Element element){
this.element = element;
}
// OverRide equals and Hashcode
// Delegate all other methods
}
並將其傳遞到集合中,好的,現在我希望課程不是最后的課程。 有效地包裝此類中的所有元素。 嗯,那個ElementWrapper是個更好的名字。
將元素添加到java.util.HashSet
,它將僅包含唯一元素。
如果只想避免重復,請使用HashSet。 如果要訂購並避免重復,請使用樹集
此外,重寫Element的equals和hashCode方法
class Element {
...
public boolean equals(Object o) {
if (! (o instanceof Element)) {
return false;
}
Element other = (Element)o;
//compare the elements of this and o like
if (o.a != this.a) { return false;}
...
}
...
public int hashCode() {
//compute a value that is will return equal hash code for equal objects
}
}
如果有可能修改元素,則發布的答案會起作用,但我不能這樣做。 我不需要排序集,因此這是我找到的解決方案。
TreeSet<Element> nt = new TreeSet<Element>(new Comparator<Element>(){
public int compare(Element a, Element b){
if ( a == b )
return 0;
if ( (a.val - b.val) > 0 )
return 1;
return -1;
}
});
for (Element elem: elements ){
nt.add(elem);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.