3

私はJavaの初心者です.ジェネリックを理解するのに苦労しています。私が理解したことで、ジェネリックを理解するために次のデモプログラムを書きましたが、エラーがあります..ヘルプが必要です。

class GenDemoClass <I,S> 
{
    private S info;
    public GenDemoClass(S str)
    {
        info = str;
    }
    public void displaySolidRect(I length,I width)
    {
        I tempLength = length;
        System.out.println();
        while(length > 0)
        {
            System.out.print("          ");
            for(int i = 0 ; i < width; i++)
            {
                System.out.print("*");
            }
            System.out.println();
            length--;
        }
        info = "A Rectangle of Length = " + tempLength.toString() + " and Width = " + width.toString() + " was drawn;";     
    }

    public void displayInfo()
    {
        System.out.println(info);
    }
}

public class GenDemo
{
    public static void main(String Ar[])
    {
        GenDemoClass<Integer,String> GDC = new GenDemoClass<Integer,String>("Initailize");
        GDC.displaySolidRect(20,30);
        GDC.displayInfo();
    }
}

型変数 I と S をIntegerandStringで置き換えるとGenDemoClass、コードが機能するように見えます..エラーは

error: bad operand types for binary operator '>'
                while(length > 0)
                             ^
  first type:  I
  second type: int
  where I is a type-variable:
    I extends Object declared in class GenDemoClass
4

4 に答える 4

2

問題は、ほとんどのオブジェクトが>演算子で機能しないことです。

Iタイプがのサブタイプでなければならないことを宣言しNumberた場合、比較でタイプIのインスタンスをintプリミティブに変換できます。例えば

class GenDemoClass <I extends Number,S> 
{


public void displaySolidRect(I length,I width)
    {
        I tempLength = length;
        System.out.println();
        while(length.intValue() > 0)
        {

        }

この時点では、必要に応じて値を変更できないため、沈没しています。length値は不変です。この目的のためにplainintを使用できます。

public void displaySolidRect(I length,I width)
    {
        int intLength = length.intValue();
        int intHeight = width.intValue();
        System.out.println();
        while(intLength > 0)
        {
           // iterate as you normally would, decrementing the int primitives
        }

私の意見では、これはジェネリックスの適切な使用法ではありません。プリミティブ整数型を使用しても何も得られないからです。

于 2012-11-15T06:42:09.873 に答える
1

instanceof使用前に確認してください

if (I instanceof Integer){ 
   // code goes here

}
于 2012-11-15T06:41:05.557 に答える
1

整数ではないものをI lengthファイルに渡すとどうなりますか? 現時点では、特定の型であるべきだと言っているわけではありません。たとえば、文字列を渡すと、この行で何が起こるでしょうか?

while(length > 0)

ここでlengthは、一般的に として非常に明確に定義した場合、 は整数であると想定していますI

于 2012-11-15T06:38:51.880 に答える
0

op は、任意の>クラスに対して有効ではありませんI

于 2012-11-15T06:40:00.227 に答える