We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Quick question: is this "casting"
Page Index Toggle Pages: 1
Quick question: is this "casting"? (Read 896 times)
Quick question: is this "casting"?
Jan 5th, 2010, 10:44am
 
Quote:
public class Vector3D {
  public float x, y, z;
  private float[] origVals;

  public Vector3D() {
  }

  public Vector3D(float x, float y, float z){
    this.x = x;
    this.y = y;
    this.z = z;

    origVals = new float[]{x, y, z};

  }



I haven't seen that kind of notation before. I'm guessing that the float values in the { } are being converted into a float array. Is that correct?
Re: Quick question: is this "casting"?
Reply #1 - Jan 5th, 2010, 10:58am
 
Basically yes the line
Code:

origVals = new float[]{x, y, z};

causes an array of floats to be created. The size of the array will be 3 because we have provided 3 initial values inside the {} brackets. It is equivalent to
Code:

origVals = new float[3];
origVals[0] = x;
origVals[1] = y;
origVals[2] = z;


This is not casting! Casting is the conversion of a variable from one data type to another e.g.
Code:

float f = 3.141589;
int i = (int) f;  // i will have the value 3


Smiley
Re: Quick question: is this "casting"?
Reply #2 - Jan 6th, 2010, 10:57am
 
Thanks! So is there any advantage to using

origVals = new float[]{x, y, z};

instead of

origVals = new float[3];
origVals[0] = x;
origVals[1] = y;
origVals[2] = z;


or

origVals = {x, y, z};

?
Re: Quick question: is this "casting"?
Reply #3 - Jan 6th, 2010, 1:53pm
 
Yes.
The advantage over the first alternative is that it is much shorter, yet remaining readable. Moreover, with lot of values, incrementing the indexes is a chore.
The advantage over the second alternative... is that it compiles! Java won't let you write that assignment, it is legal only at declaration time.
Re: Quick question: is this "casting"?
Reply #4 - Jan 7th, 2010, 10:57am
 
Thanks PhiLho & Quark, that was extremely informative. I've copied your replies verbatim onto my book
Page Index Toggle Pages: 1