Results 1 to 4 of 4

Thread: damn clone()s

  1. #1

    Thread Starter
    Addicted Member NOMADMAN's Avatar
    Join Date
    Aug 2002
    Location
    Closer than you think
    Posts
    237

    damn clone()s

    I have this chunk of code:
    Code:
    GameState [] tempGS = new GameState[7];
    
    // for each of the moves a clean gamestate.
    for ( int x=1; x<=6; x++)
         tempGS[x] = state.clone();
    Then my java compiler says:
    Incompatible type for =. Can't convert Object to GameState.

    Now I can read, obviously you can't convert GameState object to a GameState.clone() with the equals operator. So what did I do wrong? did I declare tempGS wrong, is there another way to get a copy of state (a GameState) into my array of GameStates?

    Thanks!

    NOMAD

    ps: Yes, GameState is cloneable and no I did not write it (nor can I see it (only have class))

  2. #2
    The Devil crptcblade's Avatar
    Join Date
    Aug 2000
    Location
    Quetzalshacatenango
    Posts
    9,091
    Did you try casting it?
    Code:
    tempGS[x] = (GameState)state.clone();
    Laugh, and the world laughs with you. Cry, and you just water down your vodka.


    Take credit, not responsibility

  3. #3

    Thread Starter
    Addicted Member NOMADMAN's Avatar
    Join Date
    Aug 2002
    Location
    Closer than you think
    Posts
    237
    No, I hadn't, I tried it and it worked, thanks!

    So .clone() not of the object it was made from... why is this, is casting it good code practise?

    Thanks!

  4. #4
    The Devil crptcblade's Avatar
    Join Date
    Aug 2000
    Location
    Quetzalshacatenango
    Posts
    9,091
    The reason casting was needed is because the clone() method is inherited all the way from the Object class. Since every class is inherited from the Object class, every class get the clone method.

    So the return value of clone needs to be Object, so every class can use it. Your objects are still of the GameState type, but they are treated as general Object types for usabilities sake. You'll see the same type of behavior in collections. Collections hold values of type Object so that any class can be stored there.

    Laugh, and the world laughs with you. Cry, and you just water down your vodka.


    Take credit, not responsibility

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width