简体   繁体   English

不使用HashSet从LinkedList删除重复项-Java

[英]Remove Duplicates from LinkedList without using HashSet - Java

I am attempting to remove a student from the linked list if the two students are the same, meaning a duplicate input. 如果两个学生相同,我试图从链接列表中删除一个学生,这意味着输入重复。 This is being tested with JUnit test cases. 这正在用JUnit测试用例进行测试。 However, any testing is returning the same list with no students removed. 但是,所有测试都将返回相同的列表,并且不会删除任何学生。 This is the removeDuplicate method, where list is my linkedList. 这是removeDuplicate方法,其中list是我的linkedList。

public void removeDuplicates() {

    for (int i = 0; i < list.size()-1; i++) {
        for (int j = i + 1; j < list.size(); j++) {
            if (list.get(i).equals(list.get(j))) {
                list.remove(j);
            }
        }
    }
}

An example of one of the failing test cases: 一个失败的测试用例的示例:

public void test_removeDuplicates_1() {
    ISimpleDatabase model = new SimpleDatabaseModel();
    Student s1 = new Student("John Doe", "G123456789", 3.5);
    Student s2 = new Student("Paul Graham", "G123456987", 2.75);
    Student s3 = new Student("Mary Joe", "G331456987", 3.25);
    Student s4 = new Student("Martin Fowler", "G654789321", 3.65);
    Student s5 = new Student("Paul Graham", "G123456987", 2.75);
    Student s6 = new Student("Mary Joe", "G331456987", 3.25);
    model.insert(s1);
    model.insert(s2);
    model.insert(s3);
    model.insert(s4);
    model.insert(s5);
    model.insert(s6);
    model.removeDuplicates();
    String expected = s1 + "\n" + s2 + "\n" + s3 + "\n" + s4;
    assertEquals(expected,model.toString().trim());

Which returns this error: 哪个返回此错误:

测试用例失败

I am certain the error is in the removeDuplicates() method, but I can't seem to figure it out. 我确定错误在于removeDuplicates()方法中,但我似乎无法弄清楚。 Thanks for your help. 谢谢你的帮助。

If you remove an item you need to step j back one so you test the newly shuffled-down item, otherwise you will miss it. 如果删除某个项目,则需要将j后退一步,以便测试新改组的项目,否则您将错过它。

if (list.get(i).equals(list.get(j))) {
    list.remove(j);
    j--;
}

I figured out something that works. 我发现了一些可行的方法。 I'm just checking one of the fields for duplicates because if the student id is the same, then the student is the same as well. 我只是检查重复项的字段之一,因为如果学生ID相同,那么学生也将相同。 This appears to pass all test cases now for me. 这似乎使我现在通过了所有测试用例。 Just needed some time away to figure it out. 只是需要一些时间才能解决。 Thanks everyone. 感谢大家。

public void removeDuplicates() {

    for (int i = 0; i < list.size() - 1; i++) {
        int count = i + 1;
        while (count < list.size()) {
            if (list.get(i).getGnumber().equals(list.get(count).getGnumber())) {
                list.remove(count);
            } else {
                count++;
            }
        }
    }
}

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

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