[英]how do i create a Method that accepts both String[] and Integer[] in java without method overloading?
Let's say you have an integer array and a string array. 假设你有一个整数数组和一个字符串数组。 How can you write a SINGLE method printArray that can print all the elements of both arrays.
如何编写可以打印两个数组的所有元素的SINGLE方法printArray。 The method should be able to accept both integer arrays or string arrays.
该方法应该能够接受整数数组或字符串数组。 NOTE.. I cannot use method overloading.
注意..我不能使用方法重载。 Any idea to how to go about this?
知道如何去做这个吗?
You should write a generic method 你应该写一个通用的方法
public <T> void printArray(T[] array) {
//do your printing stuff here; something like this will work
for ( T elem : array ) {
System.out.println(elem.toString());
}
}
When you call the method you just do printArray(arrayOfIntegers)
where arrayOfIntegers
is 当你调用方法时,你只需要执行
printArray(arrayOfIntegers)
,其中arrayOfIntegers
是
Integer[] arrayOfIntegers;
The only way I see is 我看到的唯一方法是
public void print(Object o) {
if (o instanceof String[]) {
System.out.println(Arrays.toString((String[]) o));
}
else if (o instanceof int[]) {
System.out.println(Arrays.toString((int[]) o));
}
}
But it's absolutely ugly. 但这绝对是丑陋的。 You should have two different methods.
你应该有两种不同的方法。
If what you have is an Integer[]
(instead of an int[]
), then it's simpler, and OK: 如果您拥有的是
Integer[]
(而不是int[]
),那么它更简单,并且可以:
public void print(Object[] o) {
System.out.println(Arrays.toString(o));
}
You can use generics: 你可以使用泛型:
public <T> void printArray(T[] array)
{
for(T elem : array) System.out.println(elem);
}
You would call it like this: 你会这样称呼它:
printArray(new Integer[] { 1, 2, 3 });
printArray(new String[] { "Hello", "World" });
You can also have a java-8 based solution like this- printAnyArray() is the required method. 你也可以使用像这样的基于java-8的解决方案 - printAnyArray()是必需的方法。
public class ArrayPrinter{
public static void main(String args[]){
String strArray[]={"a","b"};
Integer intArray[]={1,2};
printAnyArray(strArray);
printAnyArray(intArray);
}
public static void printAnyArray(Object[] objectArray){
Arrays.asList(objectArray).forEach(System.out::println);
}
}
You can do like this! 你可以这样做!
class Printer
{
public <inputType> void printArray(inputType[] array)
{
for (inputType elem: array)
{
System.out.println(elem);
}
}
}
You can use ArrayList with Object 您可以将ArrayList与Object一起使用
import java.util.ArrayList;
class Printer {
public void printArray(Object[] a) {
ArrayList<Object> al = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
al.add(a[i]);
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.