W
W
WTFAYD2016-08-16 11:13:05
Java
WTFAYD, 2016-08-16 11:13:05

How does conversion work with parameterized types?

class FixedSizeStack<T> {
  // ...
  private Object[] storage;
  // ...
  @SuppressWarnings("unchecked") 
  public T pop() { return (T) storage[--index]; }
}

public class Program {
  // ...
  public static void main(String[] args) {
    FixedSizeStack<String> strings = new FixedSizeStack<String>;
    // ... заполняем массив
    for (int i = 0; i < SIZE; i++) {
      String s = strings.pop();
      System.out.print(s + " ");
    }
  }
}

The tutorial ( Thinking in Java ) says that there is no conversion in the pop() method , since T is erased to Object , and in essence, the conversion is Object to Object . However, why is the information saved and why does this code work - outputting all String objects? I'm completely confused, up to this point there were several points about creating objects and arrays of parameterized types, and it said what a buzz conversion is:
When get() is called, the object is converted to T; it is the correct type, so the conversion is safe.

public T get(int index) { return (T)array[index]; }

Please tell me what is really going on.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
void_phoenix, 2016-08-16
@WTFAYD

Generics exist at compile time, everything is correct, and in your case there will indeed be a conversion from Object to Object.
In your case, it happened that only objects of type String are stored in the array, so it is not a problem for java to do this
String s = strings.pop();
because it is returned after the fact String.
However, if, for example, the method for adding is made as
public void put(Object object){
storage[index++] = object;
}
then it will be possible to add to the collection Object
FixedSizeStack < String > strings = new FixedSizeStack<>(2);
strings put(new Object());
then when you start taking values ​​from the collection, your program will fall with a ClassCastException in an attempt to cast the object to a string. That is, the pop method will work fine and return an Object, and already in the string
String s = strings.pop();
you end up with String s = Object
and the program will crash.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question