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 and var2.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&lt;String&gt; var1=new Clazz&lt;String&gt;();
        Clazz&lt;Integer&gt; var2=new Clazz&lt;Integer&gt;();
        // Одинаковые ли ссылки на объект?
        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 (intand different types. The programme &apos; 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> and Foo<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):

    ♪ ♪ ♪ ♪



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2