Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

语法糖章节-当泛型内包含静态变量 疑问 #2176

Open
cctyl opened this issue Sep 25, 2023 · 2 comments
Open

语法糖章节-当泛型内包含静态变量 疑问 #2176

cctyl opened this issue Sep 25, 2023 · 2 comments
Labels
perfect content improve the content

Comments

@cctyl
Copy link

cctyl commented Sep 25, 2023

当泛型内包含静态变量

原文是:
`当泛型内包含静态变量

public class StaticTest{
public static void main(String[] args){
GT gti = new GT();
gti.var=1;
GT gts = new GT();
gts.var=2;
System.out.println(gti.var);
}
}
class GT{
public static int var=0;
public void nothing(T x){}
}
以上代码输出结果为:2!

由于经过类型擦除,所有的泛型类实例都关联到同一份字节码上,泛型类的所有静态变量是共享的。`

静态变量,本身不就是全局唯一的吗,即使你通过对象访问,本质访问的还是静态变量,这与是否使用泛型没有关系啊。
为了证明这个观点,我去除了泛型,重新执行代码,依然打印2.这是因为:
GT<Integer> gti = new GT<Integer>(); gti.var=1; GT<String> gts = new GT<String>(); gts.var=2;
修改的是同一个变量。

示例如下:
`
public static void main(String[] args) throws Throwable {

    GT gti = new GT();
    gti.var=1;
    GT gts = new GT();
    gts.var=2;
    System.out.println(gti.var);
}

class GT{
public static int var=0;
public void nothing(int x){}
}

`

@Snailclimb
Copy link
Owner

当泛型内包含静态变量

原文是: `当泛型内包含静态变量

public class StaticTest{ public static void main(String[] args){ GT gti = new GT(); gti.var=1; GT gts = new GT(); gts.var=2; System.out.println(gti.var); } } class GT{ public static int var=0; public void nothing(T x){} } 以上代码输出结果为:2!

由于经过类型擦除,所有的泛型类实例都关联到同一份字节码上,泛型类的所有静态变量是共享的。`

静态变量,本身不就是全局唯一的吗,即使你通过对象访问,本质访问的还是静态变量,这与是否使用泛型没有关系啊。 为了证明这个观点,我去除了泛型,重新执行代码,依然打印2.这是因为: GT<Integer> gti = new GT<Integer>(); gti.var=1; GT<String> gts = new GT<String>(); gts.var=2; 修改的是同一个变量。

示例如下: ` public static void main(String[] args) throws Throwable {

    GT gti = new GT();
    gti.var=1;
    GT gts = new GT();
    gts.var=2;
    System.out.println(gti.var);
}

class GT{ public static int var=0; public void nothing(int x){} }

`

这块原文确实存在一些问题,欢迎提交一个PR完善一下。

@qiaoxingxing
Copy link
Contributor

提交了一个pr
#2232

@Snailclimb Snailclimb added the perfect content improve the content label Feb 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
perfect content improve the content
Projects
None yet
Development

No branches or pull requests

3 participants