如何修复通用方法中的“错误:二进制运算符的错误操作数类型”?

时间:2019-04-27 07:44:47

标签: java arrays generics generic-collections

我正在尝试在数组中打印特定范围的内容。并且,我被要求使用通用方法,但是我不断收到这些错误,指出二进制运算符的操作数类型错误。我想问一下我做错了什么部分,以及如何解决错误?

我正在使用drjava。

  Integer[ ] integerArray = { 1, 2, 3, 4, 5};
  Double[ ] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5 };
  Character[ ] characterArray = { 'H', 'E', 'L', 'L', 'O' };
  Pet[ ] petArray = { new Pet( "Bob", "Tortoise", "TSA", "19950315" ),
                      new Pet( "SweetPea", "Horse", "Genie", "20030214" ),
                      new Pet( "Little", "Chicken", "John", "20190123" ),
                      new Pet( "Dale", "Chipmunk", "Sam", "20090527" ),
                      new Pet( "Smokey", "Bear", "USPW", "19440413" )     };

  System.out.printf( "%nRange of integerArray contains:%n" );
  printRange( integerArray, 1, 3); 

  System.out.printf( "%nRange of doubleArray contains:%n" );
  printRange( doubleArray, 1, 3 ); 

  System.out.printf( "%nRange of characterArray contains:%n" );
  printRange( characterArray, 1, 3 ); 

  System.out.printf( "%nRange of petArray contains:%n" );
  printRange( petArray, 1, 3 );

} // end main

//这是我遇到错误的部分

public static <T> void printRange( T[ ] inputArray, T start, T stop ){

 // display array elements 
 // Error:bad operand type T for unary operator '++' and Error: bad operand types for binar operator

    for( T element = start; element < stop; element++ )    
    {
        //Error: bad operand types for binary operator '>='
        first type:  T
        second type: int
        // Error: bad operand types for binary operator '<='
        first type:  T
        second type: T
        //Error: bad operand types for binary operator '<'
        first type:  T
        second type: T
        if( start < stop && start >= 0 && stop <= inputArray[inputArray.length-1] )
        {
            System.out.printf( "%s", element.toString( ) );
        }

    } // end enhanced for loop

    System.out.println( );

} // end method printRange                                    
} // end class ArrayMethods

这是预期的输出。 integerArray的范围包含:

  

2 3

     

2.2 3.3

     

E

1 个答案:

答案 0 :(得分:0)

++> ..之类的操作仅适用于数字类型。您应该为intstart变量使用stop类型。复制源数组的特定范围以进行打印更容易:

public static <T> void printRange(T[] inputArray, int start, int stop) {
    T[] copy = Arrays.copyOfRange(inputArray, start, stop);
    System.out.println(Arrays.toString(copy));
}

更新:使用for循环:

for (int i = 0; i < inputArray.length; i++) {
    if (i >= start && i < stop) {
        System.out.printf("%s ", inputArray[i]);
    }
}