java – Static field in generics/template

Question:

There is a Java generics class like:

public class MyClass<T> {
   static long myField=System.currentTimeMillis();

   //blah-blah
}

Two objects are created:

MyClass<String> var1=new MyClass<String>();
MyClass<Integer> var2=new MyClass<Integer>();

question: are var1.myField and var2.myField the same?

update

And if it is a template in C++/C# – then will they be the same or not?

Answer:

Answer: Yes, they are the same for Java

Your example is not the best for demonstrating this. It is known that StringBuilder does not refer to one pool and creates a new object each time. We will use it to confirm the assertion:

public class Clazz<T> {
    static StringBuilder myField= new StringBuilder("Test text");

    public static void main (String args[]) throws InterruptedException {
        Clazz<String> var1=new Clazz<String>();
        Clazz<Integer> var2=new Clazz<Integer>();
        // Одинаковые ли ссылки на объект?
        System.out.println(var1.myField == var2.myField); 
        // Одинаковы ли содержания объектов?
        System.out.println(var1.myField.toString().equals(var2.myField.toString())); 
    }
}

Output:

true
true

In C ++, as far as I understand, there is no direct analogue of the generic class. There are templates and they work somehow differently. I wrote some code:

template <class T> class Test {
    public: static int count;
};

template <class T> int Test <T> ::count;

int main() {
    Test <int> a;
    Test <int> b;
    Test <double> c;
    a.count = 2;
    b.count = 1;
    c.count = 1;
    // Одинаковы ли ссылки?
    cout << (&a.count == &b.count) << endl;
    // Одинаковы ли содержания?
    cout << (a.count == b.count)<< endl;
    // Одинаковы ли ссылки?
    cout << (&a.count == &c.count) << endl;
    // Одинаковы ли содержания?
    cout << (a.count == c.count) << endl;

    return 0;
}

A static variable inside a template is the same for objects created by the same type ( int ) and different for different types. The output of this program is the following:

output:

1
1
0
1

There is no way to do research in C# (the OS does not support it), but I found a similar question on the English StackOverflow: Are static members of a generic class tied to the specific instance? .

Things there don't seem to be much different from C++.

A static variable is the same for all instances of the same type. Foo<int> and Foo<string> are two different types. This can be shown in the following example:

 // Результатом будет "False" Console.WriteLine(typeof(Foo<int>) == typeof(Foo<string>));

This can be found in paragraph 1.6.5 of the C# language specification (for C# 3):

….

Scroll to Top