简体   繁体   English

在这种情况下应该使用哪个集合?

[英]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. 该计划应该能够为学生添加付款详细信息,并确保没有注册重复的付款细节。

Perhaps a Map<Student, Set<Payment>> would do. 也许Map<Student, Set<Payment>>会这样做。

(A Set won't allow for duplicates.) Set不允许重复。)

If you override equals properly (and hashCode ) you can do something like 如果你正确地覆盖equals (和hashCode ),你可以做类似的事情

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.");
}

whenever you have a requirement for no duplicates, Use a Set . 每当您要求不重复时,请使用Set If you use a HashSet , make sure to implement hashCode on the Objects you put in the set (and also equals ). 如果您使用HashSet ,请确保在您放入集合中的Objects上实现hashCode (以及equals )。

您可能会发现学生地图对一组付款有帮助

Map<Student, Set<Payment>> studenthistory;

You can consider eg 你可以考虑例如

Map<Student, HashSet<Payment>> students;

Student is the student, identified by name or some ID. Student是学生,通过姓名或某些身份证明。 HashSet<Payment> are the payments. HashSet<Payment>是付款。 A Payment contains an ID, amount, date, etc. Payment包含ID,金额,日期等。

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 请记住在您的班级上覆盖equals-method: 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 :) .... 或类似的东西 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM