当前位置:  开发笔记 > 编程语言 > 正文

Java从多个Array中删除重复的内容

如何解决《Java从多个Array中删除重复的内容》经验,为你挑选了1个好方法。



1> OldCurmudgeo..:

你应该勇敢并采取OOP路线.进行class调用Student并将所有值折叠到该类中.然后你只需要把它们放在一个Set,根据定义,它不允许重复.

但是,您必须实施equalshashcode(或者Comparable如果您选择不使用HashSet).

enum Gender {

    Boy, Girl, Other;
}

enum Course {

    IT, CS;
}

class Student {

    final String name;
    final int age;
    final Gender gender;
    Course course;

    public Student(String name, int age, Gender gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    @Override
    public String toString() {
        return name + "\t" + age + "\t" + gender + "\t" + course + "\n";
    }

    @Override
    public int hashCode() {
        int hash = 5;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Student other = (Student) obj;
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        if (this.age != other.age) {
            return false;
        }
        if (this.gender != other.gender) {
            return false;
        }
        return true;
    }

}

public void test() {
    System.out.println("Hello");
    List students = Arrays.asList(
            new Student("A", 9, Gender.Boy),
            new Student("B", 10, Gender.Boy),
            new Student("B", 9, Gender.Boy),
            new Student("A", 9, Gender.Boy),
            new Student("A", 9, Gender.Girl)
    );
    // Fold it into a Set to eliminate duplicates.
    Set all = new HashSet();
    all.addAll(students);
    // Pull back out into a List.
    System.out.println("Students:\n" + all);
}

推荐阅读
有风吹过best
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有