我是数组列表的新手,想问一下我如何知道传入参数数组的类型是哪种类型(String、Int、Double..)以及如何在以下方法中处理?:
public static <T> Pair<T, Integer> mode(T items[])
第二种类型始终是一组Integers
,但 T(第一种类型)可以是任何其他类型,例如 Integer、Double、String...等。我需要提取传递到方法中最常见的字符(或数字,或字符串..)的数量。在测试文件中我有这样的内容:
@Test(timeout=2000) public void string_mode_3(){
test_mode(new String[]{"b","a","b","a","b","c","b"},
"b",4);
或
@Test(timeout=2000) public void integer_mode_1(){
test_mode(new Integer[]{30,10,10,20},
10,2);
如何确定方法 mode()
中的第一个类型是否为 Integer、Double、String?
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 <T> Pair<T, Integer> mode(T items[])
{
return
}
}
最佳答案
您实际上并不需要知道数组元素的类型即可实现此目的。请注意,您只需计算每个元素出现的次数,它们是什么类型并不重要。
这是使用泛型的优点之一:您可以创建可以透明地与许多不同类型一起使用的代码。
像这样的东西会起作用:
public static <T> Pair<T, Integer> mode(T items[]) {
// If the array is empty, return a dummy pair object
if (items.length == 0) {
return new Pair(null, 0);
}
// Create a map to store the elements count
Map<T, Integer> countFromItem = new HashMap<>();
// For each item in the array
for (T item : items) {
// Get the current count
Integer count = countFromItem.get(item);
// If there is no current count
if (count == null) {
// Set the count to 0
count = 0;
}
// Add 1 to the item current count
countFromItem.put(item, count + 1);
}
// After we found correct count for each element
T mode = null;
int maxCount = 0;
// Go through each entry (element: count) in the map
for (Map.Entry<T, Integer> entry : countFromItem.entrySet()) {
// If the this entry count is greater than the greatest count until now
if (entry.getValue() > maxCount) {
// This entry element is the mode
mode = entry.getKey();
// This entry count is the maxCount
maxCount = entry.getValue();
}
}
return new Pair(mode, maxCount);
}
关于java - 具有两种类型的Arraylist : how to determine the first type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29427182/