Check out the following class:
public class Range<T extends Comparable<T>>
{
public T lower;
public T upper;
public Range(String range){
Scanner scanner = new Scanner(range);
if(scanner.hasNextInt())
this.lower = scanner.nextInt();
if(scanner.hasNextInt())
this.upper = scanner.nextInt();
}
public String toString(){
return lower + " - " + upper;
}
}
In constructor, I'm trying to construct an object from a string. Values that the creating object contain are in String range. The string has a format like a string that is return from toString method.
This won't work so easily, the error is on last two lines of constructor, and it says: "Type mismatch: cannot convert from int to T." Ofcourse... Because the T type is decided by the user, and Scanner.nextInt() allways returns int. Even if this would work it would work only when T is int. But let's say that I'm okay if it just works when T is int.
Is there any way I can construct object of this class with such String, only when T is int. I doubt there is anything similar to class specialization like in C++.
Do you get what I want, let's say that string is "5 - 10". I want lower to be 5 and upper 10, and they need to be ints. Anyway possible.
lowerandupperbothint.int?