如何在泛型方法中修复“错误:二元运算符的错误操作数类型”?

问题描述 投票:-1回答:1

我正在尝试在数组中打印特定范围的内容。并且,我需要使用泛型方法,但我不断收到这些错误,说二进制运算符的错误操作数类型。我想问一下我做错了哪一部分,我该如何修复错误?

我正在使用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 L.

java arrays generics generic-collections
1个回答
0
投票

++> ..这样的操作仅允许用于数字类型。你应该使用int类型为startstop变量。并且复制特定范围的源数组以打印它更容易:

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]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.