📜  使用方法重载打印不同类型数组的Java程序

📅  最后修改于: 2022-05-13 01:54:45.026000             🧑  作者: Mango

使用方法重载打印不同类型数组的Java程序

在Java中,方法重载可以定义为包含多个同名方法的类,但参数列表或参数类型或方法的参数顺序不应相同。我们可以使用Java中的方法重载打印不同类型的数组,方法是确保方法包含具有相同方法名称的不同参数。

让我们实现一个程序,将 printArray() 方法重载 3 次以打印不同类型的数组。并且每次函数都有不同的参数。在 main 方法中,为每个数组提供所需的输入,然后通过调用它们各自的方法将数组打印在屏幕上。

执行:

Java
// Java Program to Use Method Overloading
// for Printing Different Types of Array
class methodOverloadingDemo {
 
    // creating a method for printing integer
    // array with integer parameter
    public static void printArray(Integer[] arr)
    {
        System.out.println("\nThe Integer array is: ");
 
        // for loop for printing the elements of array
        for (Integer i : arr)
            System.out.print(i + " ");
        System.out.println();
    }
 
    // overloading the above created method with different
    // parameter method contains a character parameter
    public static void printArray(Character[] arr)
    {
        System.out.println("\nThe Character array is: ");
 
        // for loop for printing the elements of array
        for (Character i : arr)
            System.out.print(i + " ");
        System.out.println();
    }
 
    // now the parameter for the overloaded method is String
    public static void printArray(String[] arr)
    {
        System.out.println("\nThe String array is: ");
 
        // for loop for printing the elements of array
        for (String i : arr)
            System.out.print(i + " ");
        System.out.println();
    }
 
    // now the parameter for the overloaded method is double
    public static void printArray(Double[] arr)
    {
        System.out.println("\nThe Double array is: ");
 
        // for loop for printing the elements of array
        for (Double i : arr)
            System.out.print(i + " ");
    }
 
    // main function
    public static void main(String args[])
    {
 
        // calling the parameters of all the
        // methods and taking the inputs
        Integer[] iarr = { 2, 4, 6, 6, 8 };
        Character[] carr = { 'H', 'E', 'L', 'L', 'O' };
        String[] sarr
            = { "Ram", "Nidhi", "John", "Raju", "Sara" };
        Double[] darr
            = { 10.0123, 89.123, 65.132, 78.321, 1.798 };
 
        // calling the methods and printing the arrays
        printArray(iarr);
        printArray(carr);
        printArray(sarr);
        printArray(darr);
    }
}



输出
The Integer array is: 
2 4 6 6 8 

The Character array is: 
H E L L O 

The String array is: 
Ram Nidhi John Raju Sara 

The Double array is: 
10.0123 89.123 65.132 78.321 1.798 

时间复杂度: O(N),其中 N 是数组的大小。