Simple assignment question.

I’m trying to examine an array of strings and find out which is the widest. Here’s an approximation of the code I’m using:



// The set of texts:

String [] texts = a bunch of texts

Font [] fonts = the fonts of those texts

// A variable to hold the longest line, initially set to the width of the first line:

double longestLine = ( the width of the first line, calculated using the font and the getStringBounds method) ;

// A variable to hold the current width when counting through the texts:

double currentWidth ;

// Now, counting through the texts to find the longest one:

for ( int i=1 ; i < texts.length ; i ++ ) {

     currentWidth =  ( again using getStringBounds, this time to find the width of the current line ) ;

     if ( longestLine < currentWidth )

          longestLine = new Double ( currentWidth ).doubleValue () ;

}


So, here’s my assignment question. What I really want to do in that last line is:

 longestLine = currentWidth ;

except I suspect that will make longestLine and currentWidth both pointers to the same variable, and thus longestLine will change whenever currentWidth changes. That’s not what I want. But using “new Double ( currentWidth ).doubleValue ()” seems like a really dumb way to do things. I mean, really: creating a Double from a double so that I can get a new double? That seems really roundabout. Is there a simpler way to do the same thing?

You have become madly confused about how primitives work. It doesn’t make a reference to any data at all. It just copies that value into the variable, just like you probably always thought it would!

In other words


longestLine = currentWidth;

is all you want to do on that last line.

Cas :slight_smile:

Huh. Okay, so, but let’s just say we were talking about a Point2D and not a double. In that case,

pointA = pointB

would make both pointA and pointB point to the same object, instead of copying pointB into a new object for pointA, right?

Yes.

Cas :slight_smile:

Thanks!

And to finish that thought, that situation is why the Sun Gods gave us the Object.clone() method. If you have a Point2D object and instead of assigning a second reference to it you want a reference to an identical but different object, call:

Point2D pointB = (Point2D)pointA.clone();