Challenge #2 - have a problem retaining original display order. Help!


#1

What I did:

  1. Changed CrimeLab.mCrimes to a HashMap:
    private HashMap<UUID, Crime> mCrimes;

  2. Updated CrimeLab constructor accordingly:
    mCrimes = new HashMap<>();
    ...
    mCrimes.put(crime.getId(), crime);

  3. CrimeLab.getCrime() now very simple:
    public Crime getCrime(UUID id) { return mCrimes.get(id); }

  4. Fixing getCrimes():
    public List<Crime> getCrimes() { return new ArrayList<>(mCrimes.values()); }

  5. Problem now is that list is completely mixed up!

I tried solving this by adding new member to Crime: mOriginalIndex and implementing Comparable (see listing below).
I call crime.setOrginalIndex() in the CrimeLab constructor to ensure this value is set up correctly.

Finally, I tried to update CrimeLab.getCrimes() to return a sorted list - but I’m getting build errors.

public List<Crime> getCrimes() { return new ArrayList<>(mCrimes.values()).sort(); }

I’m very new to Java - so presume this is a simple syntax error.
Any ideas?

Cheers,
Dave.

public class Crime implements Comparable<Crime> {
    private UUID mId;
    private String mTitle;
    private Date mDate;
    private boolean mSolved;
    private int mOriginalIndex;

    public Crime() {
        mId = UUID.randomUUID();
        mDate = new Date();
    }
    public UUID getId() {
        return mId;
    }
    public String getTitle() {
        return mTitle;
    }
    public void setTitle(String title) {
        mTitle = title;
    }

    public Date getDate() {
        return mDate;
    }

    public void setDate(Date date) {
        mDate = date;
    }

    public boolean isSolved() {
        return mSolved;
    }

    public void setSolved(boolean solved) {
        mSolved = solved;
    }

    @Override
    public int compareTo(Crime o) {
        return o.getOriginalIndex() - getOriginalIndex();
    }

    public int getOriginalIndex() {
        return mOriginalIndex;
    }

    public void setOriginalIndex(int originalIndex) {
        mOriginalIndex = originalIndex;
    }
}

#2

Use LinkedHashMap instead of HashMap.
LinkedHashMap retains insertion order.
If you don’t know what are hash tables or map data structures, I suggest you should read a book on data structures.
And you can google to see the difference between LinkedHashMap and HashMap in java.