Michiru
Michiru

Reputation: 179

How to read arrays from command line and display them using generic method in JAVA?

I'm working on something related to generics in java and I've found this example on the internet here. This might be a simple question but I want to find a correct answer from someone who worked with generics. This generic method takes as input argument different types of arrays and displays them. Now I want to do this by reading those arrays from command line. Can you please help me find the correct way to do it? Thanks.

public class GenericMethodTest
    {
       // generic method printArray                         
       public static < E > void printArray( E[] inputArray )
       {
          // Display array elements              
             for ( E element : inputArray ){        
                System.out.printf( "%s ", element );
             }
             System.out.println();
        }

        public static void main( String args[] )
        {
            // Create arrays of Integer, Double and Character
            Integer[] intArray = { 1, 2, 3, 4, 5 };
            Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
            Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

            System.out.println( "Array integerArray contains:" );
            printArray( intArray  ); // pass an Integer array

            System.out.println( "\nArray doubleArray contains:" );
            printArray( doubleArray ); // pass a Double array

            System.out.println( "\nArray characterArray contains:" );
            printArray( charArray ); // pass a Character array
        } 
    }

Upvotes: 0

Views: 3428

Answers (1)

peter.murray.rust
peter.murray.rust

Reputation: 38033

I think you will have to include the datatype as part of your command line, or else have a routine which detects the type by heuristics. Something like

java GenericMethodTest "doubleArray" "1.1 2.2"

where you have two args, the type and the array. Then you will need a constructor which converts the second argument from a string to an array, such as

public DoubleArray (String sin) {
    String[] ss = sin.split(" ")'
    double dd[] = new Double[ss.length];
    for (String s : ss) {
        dd[i++] = new Double(s);
    }
}

I do this sort of thing a lot in scientific programming and I usually end up with special cases for the datatypes. How does the program know what is an integer or a string or a double? You either have to tell it or you have to give it a chance to guess.

Upvotes: 2

Related Questions