需要帮助/卡在重载通用方法上

时间:2018-11-10 20:15:01

标签: java

我需要重载GenericMethodtest的泛型方法printArray,以便

  

它需要两个附加的整数参数lowsubscripthighsubscript。对此方法的调用仅打印数组的指定部分。验证lowsubscripthighsubscript。如果其中一个超出范围,则重载的printarray方法应抛出一个invalidsubscriptexception;否则,printArray应该返回打印的元素数。

     

然后修改main以在数组printArrayintegerArraydoubleArray上同时使用characterArray的两个版本。测试两个版本的printArray的所有功能。

到目前为止,这就是我所困,并且不知道从哪里开始。

public class GenericMethodTest   
{     
  public static void main(String[] args)   
  {        
     // create arrays of Integer, Double and Character  
     Integer[] integerArray = {1, 2, 3, 4, 5, 6};   
     Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};   
     Character[] characterArray = {'H', 'E', 'L', 'L', 'O'}   


     System.out.printf("%nArray integerArray contains:%n");
     printArray(integerArray); // pass an Integer array 
     System.out.printf("%nArray doubleArray contains:%n");
     printArray(doubleArray); // pass a Double array
     System.out.printf("%nArray characterArray contains:%n");
     printArray(characterArray); // pass a Character array
   }    

   // generic method printArray       
   public static <T> void printArray(T[] inputArray)      
   {
     // display array elements  
     for (T element : inputArray)   
       System.out.printf("%s ", element);

     System.out.println();
   }
} // end class GenericMethodTest   

1 个答案:

答案 0 :(得分:-1)

公共课Print {

public static void main(String[] args) {
    Integer[] intArray = { 1, 2, 3, 4, 5 };
    Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
    Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
    
    System.out.println( "Array integerArray contains:" );
    printArray( intArray ); 
    printArray( intArray , 0, 3); //1 2 3 4
    System.out.println( "\nArray doubleArray contains:" );
    printArray( doubleArray ); 
    printArray( doubleArray , 2, 4); //3.3 4.4 5.5 
    System.out.println( "\nArray characterArray contains:" );
    printArray( charArray );
    printArray( charArray , 3, 8); //exception
    
}

private static <T> void printArray(T[] arr) {
    printArray(arr, 0, arr.length-1);

}

private static <T> void printArray(T[] arr, int low, int high) {
    if(low<0 || high>arr.length-1) {
        throw new InvalidSubscriptException("Illegal lowSubscribt or highSubscribt");
    }
    for(int i=low; i<high+1; i++) {
        System.out.printf("%s ", arr[i]);
    }
    System.out.println();
}

}