frequencySet()
方法用于在一个Integer[]
中计算每个字符在一个String
中出现的频率,这个Integer[]
被封装到Counter
类中,该类重写了equals和hashcode方法。该方法应该只返回一个唯一的频率集合,但是它添加了两个Counter
对象。
从打印语句可以看出:hashcode()
返回相等的值,并且equals()
返回true
。
问题出在哪里?
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
String[] a = new String[2];
a[0]="tan";
a[1]="nat";
Set<Counter> s = frequencySet(a);
System.out.println(s.size()); // prints
System.out.println(getFreq(a[0]).equals(getFreq(a[1])) + ":" + getFreq(a[0]).hashcode() + ":" + getFreq(a[1]).hashcode() );
}
public static Set<Counter> frequencySet(String[] strs) {
Set<Counter> set = new HashSet<>();
for(String s: strs){
Counter counter = getFreq(s);
set.add(counter);
//System.out.println(s + " : " + counter.hashcode() + " : " + Arrays.toString(counter.arr) );
}
return set;
}
private static Counter getFreq(String s){
Integer[] frequency = new Integer[26];
for(char c : s.toCharArray()){
Integer a = frequency[c-'a'];
if(frequency[c-'a']==null){
frequency[c-'a']=1;
}
else{
a++;
frequency[c-'a']=a; //++frequency[c-'a'];
}
}
//System
return new Counter(frequency);
}
}
class Counter{
Integer[] arr;
public Counter(Integer[] arr){
this.arr=arr;
}
public int hashcode(){
//return Arrays.deepHashCode((Integer[])arr);
int hashcode=31;
for(int i=0;i<arr.length;i++){
if(arr[i]==null)
hashcode+=i;
else
hashcode+=31*arr[i];
}
return hashcode;
}
public boolean equals(Object o){
//return Arrays.deepEquals(arr,(Integer[])o);
Counter c = (Counter)o;
Integer[] other = c.arr;
for(int i=0;i<26;i++){
if((arr[i]==null && other[i]!=null) || (arr[i]!=null && other[i]==null)){
return false;
}
else if(arr[i]!=null && other[i]!=null && arr[i]!=other[i]){
return false;
}
}
return true;
}
}
输出:
2
true:417:417
<script src="https://ideone.com/e.js/s2LcBw" type="text/javascript" ></script>