开发者

Why can't we have generic methods inside non-generic classes?

In C# the following is valid:

public class X {
  开发者_运维技巧  public void F<T>(T t) {}
}

and do:

var x = new X();
x.F(2);

and that's not possible in Java.

I know generics work different in both languages, but I'm still wondering...

Is there a good reason for that?


The syntax is different:

public class X {
    public <T> void F(T t) {}
}


Just so you know you CAN have generic methods inside non-generic classes in Java.

It would look like this --

public class Test {

        public <T> void func(T t) {
    // do something.
            }
}

When do you call it, test.func(2) , the 2 gets autoboxed into an Integer object

EDIT : To answer your question, whatever you are asking is exactly possible in Java.


You can, just move your generic declaration.

public <T> void F(T t){}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜