satheesh
satheesh

Reputation: 1451

Which collection should be used in this scenario?

Can any one suggest me which collection to use for this scenario:

Every student has a payment history with details of payment made by the student / family. The system should ensure that no duplicate payments are there against a student account. The program should be able to add payment details for a student, and ensure that duplicate payment details are not getting registered.

Upvotes: 2

Views: 1638

Answers (5)

Jiri Kriz
Jiri Kriz

Reputation: 9292

You can consider e.g.

Map<Student, HashSet<Payment>> students;

Student is the student, identified by name or some ID. HashSet<Payment> are the payments. A Payment contains an ID, amount, date, etc.

Upvotes: 1

jorgen.ringen
jorgen.ringen

Reputation: 1325

A set would be your best choice. A set is a collection that contains no duplicate elements.

Just remember to override the equals-method on your class: http://www.javapractices.com/topic/TopicAction.do?Id=17

In your case, it will be something like:

public boolean equals(Object obj) {
    if (!obj instanceof Payment)
        return false;
    }
    Payment p = (Payment) o;
    return p.getId().equals(getId());
}

.... or something like that :)

Upvotes: 0

Jonathan Weatherhead
Jonathan Weatherhead

Reputation: 1580

You might find a Map of students to a set of payments helpful

Map<Student, Set<Payment>> studenthistory;

Upvotes: 1

aioobe
aioobe

Reputation: 420951

Perhaps a Map<Student, Set<Payment>> would do.

(A Set won't allow for duplicates.)

If you override equals properly (and hashCode) you can do something like

Map<Student, Set<Payment>> studentPayments =new HashMap<Student, Set<Payment>>();

public void addStudentPayment(Student student, Payment payment) {

    if (!studentPayments.containsKey(student))
        studentPayments.put(student, new HashSet<Payment>());

    if (studentPayments.get(student).add(payment))
        System.out.println("Payment was added");
    else
        System.out.println("Duplicate found. Payment not added.");
}

Upvotes: 6

hvgotcodes
hvgotcodes

Reputation: 120178

whenever you have a requirement for no duplicates, Use a Set. If you use a HashSet, make sure to implement hashCode on the Objects you put in the set (and also equals).

Upvotes: 3

Related Questions