如何在参数化函数中设置一个包含任意类型的列表?

huangapple go评论97阅读模式
英文:

How to set in parametr funciton a List of any types?

问题

我有一个类似这样的函数:

public static String getNumberOfItemsInList(Order[] orders) {
     return String.valueOf(objects.length);
}

我必须在许多场景中使用这个函数:

getNumberOfItemsInList(订单列表);
getNumberOfItemsInList(用户列表);
getNumberOfItemsInList(服务列表);

如何向函数的参数中传递一个能够接受任何给定类型的 List 呢?我不想为列表的每种类型创建一个函数,有人可以帮帮我吗?

英文:

I have a function like this:

public static String getNumberOfItemsInList(Order[] orders) {
     return String.valueOf(objects.length);
}

I must use this function in many options:

getNumberOfItemsInList(list of ordres);
getNumberOfItemsInList(list of users);
getNumberOfItemsInList(list of services);

How to pass in the parameter of the function List that would take any type we give it? I don't want to create a function for any type of the list,
can somebody help me?

答案1

得分: 1

写两个方法,这样你就涵盖了“列表”的定义:

```lang-java
public static String getNumberOfItemsInList(Object[] array) {
     return String.valueOf(array.length);
}

public static String getNumberOfItemsInList(Collection<?> coll) {
     return String.valueOf(coll.size());
}

第一个方法可以处理所有类型的数组,第二个方法可以处理所有类型的集合,包括所有类型的列表。


<details>
<summary>英文:</summary>

Write 2 methods, so you&#39;re covered regarding the definition of &quot;list&quot;:

```lang-java
public static String getNumberOfItemsInList(Object[] array) {
     return String.valueOf(array.length);
}

public static String getNumberOfItemsInList(Collection&lt;?&gt; coll) {
     return String.valueOf(coll.size());
}

The first can handle all types of arrays, and the second can handle all types of collections, including all types of lists.

答案2

得分: 0

尝试这个

public static String getLength(T[] items) {
return String.valueOf(items.length);
}


<details>
<summary>英文:</summary>

try this

public static <T> String getLength(T[] items) {
return String.valueOf(items.length);
}

    

</details>



huangapple
  • 本文由 发表于 2020年9月25日 17:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64061535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定