gpt4 book ai didi

java - 如何从数组中获取最常见的字符(泛型)

转载 作者:太空宇宙 更新时间:2023-11-04 13:59:37 24 4
gpt4 key购买 nike

假设(new Integer[]{10,10,20,10,20,30,10,20,30,40,50,10,20,30,40,50,60})传递给方法public static <T> Pair<T, Integer> mode(T items[]) 。该方法应返回 10, 5 (数组中有五个数字 10)。S,基本上该方法返回数组中最常见的元素。我应该如何完成这个方法?请不要MAPS , COLLECTIONS , HashSets允许,仅ArrayLists .

      import java.util.ArrayList;

public class Mode {

public static <T> Pair<T, Integer> mode(T items[])
{
ArrayList <Pair<T, Integer>> temp = new ArrayList<>();
//ArrayList <T> temp = new ArrayList<>();

for(T values: items)
{
temp.add((Pair<T, Integer>) values);
}

for(int i = 0; i < temp.size(); i++)
for(int j = 0; j < temp.size(); j++)
{
if(temp.get(i) == temp.get(j))
}
}
}


public class Pair<X,Y>{
private X first;
private Y second;

public Pair(X x, Y y){
this.first = x;
this.second = y;
}

public X getFirst(){
return this.first;
}
public Y getSecond(){
return this.second;
}

public boolean equals(Object o){
if(!(o instanceof Pair)){
return false;
}
Pair p = (Pair) o;
return
this.first.equals(p.first) &&
this.second.equals(p.second);
}

public String toString(){
return String.format("(%s,%s)",first,second);
}

}

最佳答案

迈克,请尝试以下操作:

import java.util.ArrayList;
public class Mode {

public static Pair<T, Integer> mode(T[] a)
{

int count = 1, tempCount;
T popular = a[0];
T temp;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 1;
for (int j = 1; j < a.length; j++)
{
if (temp.equals(a[j]))
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return new Pair(popular, new Integer(count));
}
}


public class Pair<X,Y>{
private X first;
private Y second;

public Pair(X x, Y y){
this.first = x;
this.second = y;
}

public X getFirst(){
return this.first;
}
public Y getSecond(){
return this.second;
}

public boolean equals(Object o){
if(!(o instanceof Pair)){
return false;
}
Pair p = (Pair) o;
return
this.first.equals(p.first) &&
this.second.equals(p.second);
}

public String toString(){
return String.format("(%s,%s)",first,second);
}

}

如果您有任何疑问,请告诉我。

关于java - 如何从数组中获取最常见的字符(泛型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com