簡體   English   中英

比較ArrayList Java中的部分對象

[英]Compare partial object in an ArrayList Java

我有一個Object如下:

public class Record{
    Int ID;
    String title;
    Date date;
    Duration time;

    public Record createRecord(int ID, String title, Date date, Duration time){
        this.ID= ID;
        this.title = title;
        this.date = date;
        this.time = time;
        return this;
    }
}

我在List中存儲多個對象。 在插入新記錄時,我需要檢查列表是否已經有一個只有相同標題和日期的對象,並替換它中的時間。

我正在尋找任何可以實現O(1)時間的解決方案。

在ArrayList中搜索現有元素將在排序的ArrayList的情況下獲取O(n)(例如,您保持記錄已排序),它將需要O(logn)時間。 因此,為了實現所需的功能,我使用Map結構,按標題索引,然后按日期。 像這樣的東西:

// Create general records DB
Map<String, Map<Date, Record>> records = new HashMap<>();

// Create sub DB for records with same ID
Map<Date, Record> subRecords = new HashMap<>();

// Assuming you've got from somewhere id, title and rest of the parameters
subRecords.put(recordDate, new Record(id, title, time, duration));
records.put(recordId, subRecords)

// Now checking and updating records as simple as
sub = records.get(someTitle); // Assuming you've got someTitle
if (sub != null) {
   record = sub.get(someDate); // Same for someDate
   if (record != null) {
       record.updateTime(newTime);
   }
}

使用Map Map可以防止你需要覆蓋equals和hashCode方法,而我同意Map<String, Map<Date, Record>>可能看起來有點花哨或奇怪。 雖然將為您提供更新記錄或在O(1)時間內檢查是否存在的能力。 另外一點是,您不需要創建記錄來檢查是否存在或更新,您可以直接使用標題和日期來檢索您需要的內容。

你可以通過HashSet來做到這一點

並實施

@Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if(!(obj instanceof Record)) return false;
        Record otherRecord = (Record)obj;
        return (this.time.equals(otherRecord.time) && this.title.equals(otherRecord.title));
    }

    @Override
    public int hashCode() {        
        int result = titile != null ? titile.hashCode() : 0;
        result = 31 * result + (time != null ? time.hashCode() : 0);
        return result;

    }

並使用hashset插入

   HashSet hset = new HashSet<Record>();
   if(!hset.add(record)){
        hset.remove(record);
        hset.add(record);
   }

然后你可以將HashSet轉換為你想要的List。

使用一個允許O(1)訪問的Map實現,如HashMapConcurrentHashMap

偽代碼:

class Record {
    static class Key {
        Date date
        String title
        // proper hashCode and equals
    }
    Date date
    String title
    int id
    Time time
    Key getKey() {...}
}


Map<Record.Key, Record> recordMap = new HashMap<>();
for (record : records) {
    recordMap.merge(record.getKey(), record, 
                   (oldRecord, newRecord) -> oldRecord.setTime(newRecord.getTime()));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM