I am using JAVA to program a replica of a program that I have in VB.NET. I was creating the "DataGrids" (using JTable's) and programming Tooltips to appear on the cells of my JTable... yep, in JAVA you have to do everything from scratch.
Ok, my curiosity begins when writing the following lines of code an error is hung in the program:
DataGridMed = new JTable(){
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col){
Component c = super.prepareRenderer(renderer, row, col);
if(c instanceof Component){
JComponent jc = (JComponent) c;
jc.setToolTipText((String) getValueAt(row,col)); <--- ERROR
}
return c;
}
};
I was a little indignant, because when I do a casting like that, am I not converting that value into a String object? When I change that line to .toString(), the error disappears completely...!
jc.setToolTipText(getValueAt(row,col).toString);
I clearly know that "String" is a class, and that it does not belong to the group of primitive data types (int, boolean, float, double . . . ). That's why when comparing two Strings, the "==" operator doesn't work and you need to use ".Equals()"... But in this case I'm not distinguishing what is the difference between casting and using . toString().
Exactly what happened here?
If you go to the documentation
Java
for the sectionJTable
you can see that the methodgetValueAt
returns aObjeto
:therefore, when trying to cast, it is trying to generate the
String
directly from the object and, if it does not extend fromString
, it will not be possible to cast.However, the method
toString
calls the methodtoString
found on all the data that inherits fromObject
, and this method does render an Object representation in the form ofString
.So with the first method you get an error if the cast can't be correct. However, with the second one you will not get an error since the data type you introduce is a
String
which is what the method needssetToolTipText
.First, the easy.
toString()
it is simply a method that returns a representation of the object asString
. Since it's part of the definition ofObject
, all classes have that method (although the basic implementation isn't much help). That is, for any object, you can makeobjeto.toString()
and get aString
.(String)
does a cast to String. When you have a reference to an object, when making an assignment to a subclass variable, you have to specify thecast
. The class of the object doesn't change , if you try to make ancast
aString
of an object that isn't aString
, then at runtime it throws an exception(ClassCastException
). it works like thisAs they already said:
.toString()
<-- is a method that returns the textual representation of an objectString
<-- is an Object (String data type)When using
(String)objeto
what is intended is to convert said object toString
directly and there may be conversion errors, when using.toString()
<-- It will always convert the object to aString
, although sometimes it does not return the expected value.