Static field in generics/template
-
There are Java generics like:
public class MyClass<T> { static long myField=System.currentTimeMillis();
//blah-blah
}
Two facilities are established:
MyClass<String> var1=new MyClass<String>();
MyClass<Integer> var2=new MyClass<Integer>();
Question: Are the same?
var1.myField
andvar2.myField
?Update
And if it's a C++/C# template, then they'll be the same or not?
-
Answer: Yeah, they're the same for Java.
Your example is not the best way to show it. We know that
StringBuilder
doesn't use one pool and creates a new facility every time. We'll use it to confirm that: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
C+++, as far as I understand, there is no direct analog of generic class. There are templates and they work differently. I threw a little 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;
}
The static variable inside the template is the same for objects designed by the same type (
int
and different types. The programme ' s conclusion is as follows:Output:
1
1
0
1
In C#, there's no way to do a study, but I found a similar question about English-speaking StackOverflow: https://stackoverflow.com/questions/3037203/are-static-members-of-a-generic-class-tied-to-the-specific-instance ♪
It doesn't seem to be much different from C++.
Static variable is the same for all copies of the same type.
Foo<int>
andFoo<string>
- two different types. This can be seen in the following example:// Результатом будет "False"
Console.WriteLine(typeof(Foo<int>) == typeof(Foo<string>));
This can be found in 1.6.5 of the C# Language Specification (for)
C# 3):♪ ♪ ♪ ♪