该方法是一个java.util.Collections类方法。它计算给定列表中指定元素的频率。它重写equals()方法以执行比较,以检查指定的Object与列表中的Object是否相等。
用法:
public static int frequency(Collection c, Object o) parameters: c: Collection in which to determine the frequency of o. o: Object whose frequency is to be determined. It throws Null Pointer Exception if the Collection c is null.
// 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()
上面提到的方法对于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
相关用法
- Java Java.util.Collections.rotate()用法及代码示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代码示例
- Java Java lang.Long.lowestOneBit()用法及代码示例
- Java Java lang.Long.byteValue()用法及代码示例
- Java Java.util.Collections.disjoint()用法及代码示例
- Java Java lang.Long.highestOneBit()用法及代码示例
- Java Java lang.Long.builtcount()用法及代码示例
- Java Java lang.Long.reverse()用法及代码示例
注:本文由纯净天空筛选整理自 Java.util.Collections.frequency() in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。