Java Java.util.Collections.frequency()方法及应用
该方法是java.util.Collections类的一个方法。它计算给定列表中指定元素的频率。它覆盖了equals()方法来进行比较,检查指定的对象和列表中的对象是否相等。
语法
public static int frequency(Collection c, Object o)
参数:
c: 集合,用来确定o的频率。
o: 要确定其频率的对象。
如果集合c是空的,它将抛出空指针异常。
// Java program to demonstrate
// working of Collections.frequency()
import java.util.*;
public class GFG
{
public static void main(String[] args)
{
// Let us create a list with 4 items
ArrayList<String> list =
new ArrayList<String>();
list.add("code");
list.add("code");
list.add("quiz");
list.add("code");
// count the frequency of the word "code"
System.out.println("The frequency of the word code is: "+
Collections.frequency(list, "code"));
}
}
输出:
The frequency of the word code is: 3
使用Java.util.Collections.frequency()自定义对象的Collections.frequency()
上面所说的方法对java中已经定义的对象很有效,但对自定义定义的对象呢。好吧,要计算java中自定义对象的频率,我们将不得不简单地覆盖equals()方法。让我们看看我们如何做到这一点。
// Java program to demonstrate working of
// Collections.frequency()
// for custom defined objects
import java.util.*;
public class GFG
{
public static void main(String[] args)
{
// Let us create a list of Student type
ArrayList<Student> list =
new ArrayList<Student>();
list.add(new Student("Ram", 19));
list.add(new Student("Ashok", 20));
list.add(new Student("Ram", 19));
list.add(new Student("Ashok", 19));
// count the frequency of the word "code"
System.out.println("The frequency of the Student Ram, 19 is: "+
Collections.frequency(list, new Student("Ram", 19)));
}
}
class Student
{
private String name;
private int age;
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 int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public boolean equals(Object o)
{
Student s;
if(!(o instanceof Student))
{
return false;
}
else
{
s=(Student)o;
if(this.name.equals(s.getName()) && this.age== s.getAge())
{
return true;
}
}
return false;
}
}
输出:
The frequency of the Student Ram,19 is: 2
极客教程