Answer the question
In order to leave comments, you need to log in
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 + " ");
}
}
}
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]; }
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question