I tried to cast String to T type, but it says "Inconvertible types; cannot cast 'java.lang.String' to 'T'. However, when I remove "< T >" from < T extends Comparable< T > >, and fix that to < T extends Comparable >, it is okay. What is the difference? Below is the code:
public class Graph<T extends Comparable<T>> {
public void createGraph(Scanner in) {
String line;
String[] elements;
while (in.hasNextLine()) {
line = in.nextLine();
elements = line.split("\\s+");
insertVertex((T)elements[0]); // << This is the part
}
Your graph is of type T
. That means I can have a graph of Person
s, for example.
Then, in createGraph
, you try to insert a String
vertex in the graph. But String
cannot be cast to a Person
.
If you want a createGraph
method that creates a Graph<String>
, then you need it to make it static
, like this:
public Graph<String> createGraph(Scanner in) {
String line;
String[] elements;
Graph<String> graph = new Graph<>();
while (in.hasNextLine()) {
line = in.nextLine();
elements = line.split("\\s+");
graph.insertVertex(elements[0]);
}
// ...
// Anything else, like adding edges
// ...
return graph;
}
EDIT: The reason your code compiles with no problem when you remove the <T>
in Comparable<T>
is that it becomes a graph of Comparables (instead of a graph of persons or a graph of strings), and then there's no problem in adding both a String and a Person to it.