Java中Collections的frequency方法


注:調用此方法時需要根據自己的須由復寫Objects的equals方法

創建復寫了equals方法的對象類

public class Student {

    private String name;
    private int age;

    public Student() {
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        Student s = (Student) obj;
        return this.name == s.name && this.age == s.age;
    }
}

調用

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StudentTest {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<Student>();
        list.add(new Student("林青霞", 27));
        list.add(new Student("風清揚", 30));
        list.add(new Student("劉曉曲", 28));
        list.add(new Student("武鑫", 29));
        list.add(new Student("林青霞", 27));
        
        int count=Collections.frequency(list, new Student("林青霞", 27));
        System.out.println(count);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM