Vector clone references the same objects??

Hi all
I'm developing a simple chess program.
Obviously, each move the user tries must be checked against the following sets of chess rules:
1.) Whether it is that colour player's turn to move
2.) Whether this move is valid for this specific piece (eg. 3 forward for a King --> invalid of course)
3.) Whether this move will jeopardize the player's king (put it in check)
If from any of the above the move is found to be invalid, the move is not executed.
My program structure is briefly this:
A. abstract super class 'ChessPiece' - subclassed by the various specific Chess Piece classes.
Each of the specific ChessPiece subclasses must implement an abstract method to check if a
proposed move is valid, and also a method to actually do the move...
B. 'PieceManager' class - has a Vector of ChessPieces:
This class checks whether the given move is valid:
For the piece: by calling the checking method (see A above)
For the general game: by making sure the given move doesn't put the player's king in check.
NOTE: In chess (for those who don't know), it is illegal to move any piece if, at the end of
the move, your king will be in check [possible to be captured by any enemy piece]
This last check I want to do in the following way:
1) copy/clone the entire PieceManager object
2) in this copied object, actually do the move
3) still in the copied/cloned object, see if the moving player's king is now in check
4) based on this evaluation, execute the move in the original PieceManger object or don't...
The Problem:
When I clone this PieceManager object, its 'pieces' Vector is obviously also cloned.
BUT it seems that the cloned 'pieces' Vector references the same ChessPiece objects
as those referenced by the original 'pieces' Vector; ie the 2 Vectors are sharing the same Objects.
Thus, when I actually execute the move in the test/cloned PieceManager object,
the original PieceManager's corresponding piece is moved too (well, it seems it is the same piece...).
I am pretty stuck with this.
I've tried the Vector clone method; it doesn't seem to copy the objects, but create another reference
to the same objects, as I've said.
I've tried cloning the entire object ; also not helping......
I'd love any comments, helpful pointers, suggestions.
Also any comments on my program structure... is a Vector the best tool for this job?
Thanks very much -
lutha

Hi all, OP here.
Ok thanks guys for all your posts...
two points:
1) I have tried the "copy constructor", and it seems to be doing the same thing. (ie 'shallow clone')
What's really frustrating me is that nothing I do seems to actually physically copy the Vector's objects
to new, separate copies of those objects...
I had my PieceManager class implement Cloneable (just in case - not too sure on that one; in fact I
commented that out later), and I overrode the clone method like this:
public Object clone ()
        PieceManager pm = new PieceManager ();
        Vector pcs = new Vector ();
        // Enumeration e = pieces.elements ();
        //while (e.hasMoreElements ())
        //    ChessPiece p = (ChessPiece) e.nextElement ();
        //pcs.add ();
        //}  // still references the same objects!!
        pieces.trimToSize ();
        int size = pieces.size ();
        Object[] arr = new Object [size];
        Object[] initial = pieces.toArray ();
        System.arraycopy (initial, 0, arr, 0, size);
        for (int i = 0 ; i < size ; i++)
            ChessPiece p = (ChessPiece) arr ;
pcs.add (p);
pm.pieces = pcs;
return pm;
This all still does the same 'shallow cloning'...
2) m.winter, my ChessPiece objects are not immutable - they have a co-ordinate field that
changes as they are moved. This is for getting as called by another object, and for checking in
the ChessPiece's own internal method for checking whether the passed-in square co-ordinate
is a valid destination.
Anyway, I don't think that's the main issue here. How can I properly clone/copy a Vector, resulting
in :
a) the original Vector
b) a new, totally unrelated Vector.
Thanks again all for your input.
regards,
lutha

Similar Messages

  • Two string references pointing to the same object

    Look at the following code snippet         String   s1 = "hello";
            String   s2 = "world";
            String   s3 = "welcome";
            String   s4 = "here";
            String   s5 = "hello";
      They say that references s1 and s5 point to the same object "hello".
    At run time after creating objects from s1 to s4 how the Java run time knows that there is already an object "hello" and assigns a differernt reference.

    When the jvm load the class file, all suchconstants
    found in the class are loaded in a global constant
    pool. when you assign the constant to a variable,it
    uses the same one from the constant pool.Suppose I intialize a string by getiing input
    nput from the console which already exists, in that
    case a new object will be created or the existing one
    be used.A new object will always be created in that case, but you can get a reference to the string in the pool by calling intern. See the javadoc for intern in the String class.
    Kaj

  • How can I use the same object in the different jsp files?

    I am doing a project. I have finished my jave source files and compiled them successfully. And I also wrote a main method to test my classes, they also worked well. Now I am trying to use my jave code in the jsp files. But I meet a problem, in my method of java source file, I can generate a object of a class, and use it in the whole main method. But in the different jsp files, how can I do same thing?
    For example, in the .java file,
    Vector vl = new Vector();
    While ...{
    vl.add(...)
    In each of my .jsp file I want to do one loop of the above, meanwhile I want to do that in the same object.
    I hope you can understand what I mean. Really need your help!

    put your object into a session and you can the use it in all the jsps as long as the session is valid. Or you could create a static variable in the class that only creates one instance off an object and then create a static method to return this object.

  • Make sure 2 threads share the same object

    I have been thinking about this for quite some time. However, I really couldn't figure it out due lack of experience and knowledge.
    I just needed to know how can I make sure that 2 or more threads (after certain checkings that they should share a same common object) will really share the same object.
    For example (to UlrikaJ if you are reading this):
    How can I achieve the following?? Thanks!
    "When James and Ada separately want to access their shared account,two transactions are started that accesses the object associated with that account number."

    Thanks for the answer. You are welcome :-)
    public class Account
       public Account getAccount(String userInput)
         // Some processes to verify the userInput go here.
         return account;
    }//End of Account class
    public UserThread implements Runnable
       private String name;
       private Semaphore s;
       private Account userAccount; //Reference for the Account class
       public UserThread(String name, Semaphore s)
          this.name = name;
          this.s = s;
       }//End of constructor
       public void run()
          for(;;)
              getUserInput(); //Ofcourse the implementation will depend on what you are doing
              s.lock(); //obtain a lock on Semaphore object
              //Entering critical section of the code
              this.userAccount = accountObject.getAccount(userInput);
              //End of critical section of the code.
              s.signal(); //Release the lock so that other thread
              //can access the getAccount() method...irrespective of the
              //variable or the object being used or referred to.
          }//End of for() loop
       }//End of run() method
    } //End of UserThread class
    public class AccountApplication
       public static void main(String args[])
          Semaphore sem = new Semaphore(0);
          //Always initialize the Semaphore with 0 when you create it.
          UserThread user1 = new UserThread("User Number 1",sem);
          UserThread user2 = new UserThread("User Number 2",sem);
          //All threads share the same Semaphore object
          Thread userThread1 = new Thread(user1);
          Thread userThread2 = new Thread(user2);
          userThread1.start();
          userThread2.start();
       }//End of main() method
    }//End of classWell, I have given the outline of the code. I have not compiled or run the program so it might have errors in its syntax.
    Obviously, you will definitely have to change it to suit your requirements. I have just shown you how to protect yur codes' critical section.
    Hope this clears your doubts.
    Vijay :-)

  • Error while activating XI App:  references the inactive object

    Guys,
    I am getting this error when I am activating my XI application .
    <i><b>Activation of the change list canceled Check result for Message Mapping Stockquote_Request_Map_01 | http://sapteched/XI/sessionid_XI251/inb/student_01:  Object Message Mapping Stockquote_Request_Map_01 | http://sapteched/XI/sessionid_XI251/inb/student_01 references the inactive object RFC Message ZGET_STOCKQUOTE | urn:sap-com:document:sap:rfc:functions | ZGET_STOCKQUOTE Check result for Message Mapping Stockquote_Response_Map_01 | http://sapteched/XI/sessionid_XI251/inb/student_01:  Object Message Mapping Stockquote_Response_Map_01 | http://sapteched/XI/sessionid_XI251/inb/student_01 references the inactive object RFC Message ZGET_STOCKQUOTE | urn:sap-com:document:sap:rfc:functions | ZGET_STOCKQUOTE.Response</b></i>

    Hi Manish,
    Make sure you have saved and activated all your dependent objects. If you have imported RFC structure then check
    for e.g. ZGET_STOCKQUOTE is your imported RFC structure then make sure its saved and activated.
    Then try activating your message mapping.
    Regards,
    Sridhar

  • How do I use multiple classes to access the same object?

    This should be staightforward. I have and object and I have multiple GUIs which operate on the same object. Do all the classes creating the GUIs need to be inner classes of the data class? I hope this question makes sense.
    Thanks,
    Mike

    public final class SingletonClass {
    private static SingletonClass instance;
    private int lastIndex = 10;
    public final static SingletonClass getInstance()
    if (instance == null) instance = new SingletoClass();
    return instance;
    public int getLastIndex() {
    return lastIndex;
    }1) This won't work since one could create a new SingletonClass. You need to add a private constructor. Also, because the constructor is private the class doesn't have to be final.
    2) Your design isn't thread-safe. You need to synchronize the access to the shared variable instance.
    public class SingletonClass {
        private static SingletonClass instance;
        private static Object mutex = new Object( );
        private int lastIndex = 10;
        private SingletonClass() { }
        public static SingletonClass getInstance() {
            synchronized (mutex) {
                if (instance == null) {
                    instance = new SingletonClass();
            return instance;
        public int getLastIndex() {
            return lastIndex;
    }if you are going to create an instance of SingletonClass anyway then I suggest you do it when the class is loaded. This way you don't need synchronization.
    public class SingletonClass {
        private static SingletonClass instance=new SingletonClass();
        private int lastIndex = 10;
        private SingletonClass() { }
        public static SingletonClass getInstance() {
            return instance;
        public int getLastIndex() {
            return lastIndex;
    }If you don't really need an object, then you could just make getLastIndex() and lastIndex static and not use the singleton pattern at all.
    public class SingletonClass {
        private static int lastIndex = 10;
        private SingletonClass() { }
        public static int getLastIndex() {
            return lastIndex;
    }- Marcus

  • The same Object Version Number for the same person id multiple times

    Hello all,
    I am currently facing an issue with HRMS tables and the object version number for employees. I am trying to write a report but due to the same object version number for the same person appearing in several row i am getting duplicate information. For example,
    person id 91 object version number 32 is on 4 rows and i have no idea why...help please guys, I'm at a lost so far 50 people are facing the same issue.

    Hi Baal666bobo,
    The person table is date-tracked, so the PK has effective start and end dates as well.
    Get the correct record with sysdate(or any particular date) and then check the OVN.
    Cheers,
    Vignesh

  • Multiple Transports for the Same Object.

    I have ABAP program 123 and I make a change, create transport A and release the transport. I do not request transport A go to production.
    I then modify ABAP program 123 again, create transport B and release the transport. I do not request transport B go to production.
    Now I request transport A go to production.
    Can someone explain to me why the changes in transport B are included when transport A is moved to production?
    I thought each transport would be at its own change level.
    Thank-you.

    I can guarantee all of you that when Transport A was moved, it contained changes that were made in Transport B.
    Surely you understand that Thomas is correct and that there's a logical reason, not related to transport layer configuration, for the issue?   You CAN have multiple transports open for the same object without a lock by forcing it but check the dates as already suggested...

  • Can we have multiple transports for the same object.

    Hi guys,
    Can we have multiple transports for same object in dev system. Can anyone tell me how can this be done.
    Thanks

    Its not possible for the same development object. Only 1 person can access an object at a time and if mutiple users modify an object new TASKs are created under the same TRANSPORT.
    Only after releasing the tr you can create a new tr on the same object.
    Message was edited by:
            Abhishek Jolly

  • Two Threads Sharing the Same Object

    I am learning Java multithreading recently and I really hit the wall when I came to synchronizing data using the synchronized keyword. According to the explanation, synchronized will only work when 2 or more threads are accessing the same object. If there are accessing 2 different objects, they can run the synchronized method in parallel.
    My question now is how to make sure for synchronized method to work, I am actually working with the same and only one object??
    Imagine this:
    Two person with the same account number are trying to access the very ONE account at the same time.
    I suppose the logic will be:
    Two different socket objects will be created. When it comes to the login or authentication class or method, how can I make sure in term of object that the login/authentication class or method will return them only ONE object (because they share the same account), so that they will be qualified for using the synchronized method further down the road?
    Thanks in advance!

    Actually your understanding is wrong. Consider:
    public class MyClass {
      private int someInt;
      private float someFloat;
      private synchronized void someMethod(final int value) {
        if (value > 2000) someInt = 2000;
      private synchronized void someOtherMethod(final float value) {
        if (value > 2.0) someFloat = 1.999f;
    }YOu might think that two different threads can enter this code, one can enter in someOtherMethod() while one is in someMethod(). That is wrong. The fact is that synchronization works by obtaining synchronization locks on a target object. In this case by putting it on the method declaration you are asking for the lock on the 'this' object. This means that only one of these methods may enter at a time. This code would be better written like so ...
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized(someInt) {
          if (value > 2000) someInt = 2000;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) someFloat = 1.999f;
    }In this manner you are only locking on the pertinent objects to the method and not on 'this'. This means that both methods can be entered simultaneously by two different threads. However watch out for one little problem.
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized(someInt) {
          if (value > 2000) {
            someInt = 2000;
            synchronized (someFloat) {
              someFloat = 0.0f;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) {
            someFloat = 1.99999f;
            synchronized (someInt) {
              someInt = 0;
    }In this case you can have a deadlock. If two threads enter one of these methods at the same time one would be waiting on the lock for someInt and the other on the lock for someFloat. Neither would proceed. The solution to the problem is simple. Acquire all locks in alphabetical order before you use the first.
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized (someFloat) {
          synchronized(someInt) {
            if (value > 2000) {
              someInt = 2000;
              someFloat = 0.0f;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) {
            someFloat = 1.99999f;
            synchronized (someInt) {
              someInt = 0;
    }In this manner one thread will block waiting on someFloat and there can be no deadlock.

  • Multiple inserts for the same object

    We have observed that in certain cases, the same object is attempted to be inserted twice, resulting in Primary Key violation.
    Here is one example -
    A(1->1)B, unidirectional, A has the foreign key to B
    new B
    copyB = register(B) (also assign sequence number)
    new A1, A2
    A1.set(copyB), A2.set(copyB)
    register(A1), register(A2)(also assign sequence number)
    commit
    it tries to insert the same B twice.
    any clues whats wrong here?
    thanks

    Any chance your 1:1 from A to B is marked as privately-owned?
    This would indicate to TopLink that the object in each relationship is unique and should be inserted.
    Doug

  • SSDT Schema Compare keeps showing the same objects as different..

    Hi, 
    When comparing a database to my project using Visual Studio 2012 SSDT I get several stored procedures marked as changed. The body of the procedures is identical, but two properties are highlighted as different when expanding the object:
    IsSelf (false on the DB vs true on the project) and User  (dbo on the DB, needs to be added to the project).
    The procedures have the option "with execute as self" both in the database and in the project as part of the body.
    I have not found what needs to be done so these differences are applied to the project and never appear again. Tried changing some options on the schema compare but didn't found one that help. 
    Some forum suggested dropping the objects and re-creating them but I don't want to loose the history of changes on TFS.
    Any suggestions? 

    Hi Daniel,
    Since you have posted this issue to the SSDT forum here:
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/5c9c5c47-64ac-4af4-9104-c9500dc8cf52/ssdt-schema-compare-keeps-showing-the-same-objects-as-different?forum=ssdt#5c9c5c47-64ac-4af4-9104-c9500dc8cf52
    I will move this thread to the Off-topic forum, thanks for your understanding.
    Sincerely,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Fact table have tow column reference the same dim table

    In my analytic domain, my fact table have tow column reference the same dim table, but in physical diagram, between two table ,can only have one join, so i create a copy of the dim table, then finish the join in physical. This method can resolve this question, but not so good, Anyone have perfect solution?

    user4497169 wrote:
    Thanks,
    yours method is very very good, I don't know this method before. Where do you get this imfomation?The sample sales RPD has (good) modelling references you can refer to, otherwise think about how you'd write the SQL Statement yourself, you'd need to use an alias to access the same table on seperate joins.

  • LMDB - SLD "Source and target system have the same object server name"

    Hi,
    the system is a SM7.1 SP1
    For some reason (Object-Server-Name changed), the job that syncs the sld and lmdb cancels...
    I set the LMDB-Object-Server-Name to its original Name...
    Now i've deleted the sync-config in the solman_setup and try to start a new sync, but i get the following error, when i try to configure the source-system:
    'Source and target system have the same object server name: CISM318'
    But the names are different: 'SM3' (LMDB) and 'CISM318' (SLD)
    Any suggestions ?
    best regards
    Christoph
    Edited by: Christoph Bastian on Aug 26, 2011 9:37 AM
    Edited by: Christoph Bastian on Aug 26, 2011 11:18 AM

    problem solved...
    Apparently the sync needs some hours to finish a object-server-name-change...
    best regards
    Christoph

  • How do I get citations to reference the same endnote?

    I have a Pages document with small uppercase numbered endnotes that reference the same book or artilce in the bibliography at the end of the document.  I want it to read something like this simple sample text:
    Stars are big balls of hot glowing gas (1). Our sun is an average star (2). Blue white stars are hotter than red stars (1) The surface of our sun is hotter than the center.(2)
    1. Joe's Book on Stars. Stellar Publishing 2014
    2. Our Sun. Solar Publishing 2014
    The problem is I can only get the small uppercase endnotes in the text to be consecutive 1,2,3,4, 5, etc. I don't want this. I want to be able to have some piece of text linked to the same number in the bibliography at the end so that the text citations could be something more like the simple example above like, 1, 2,3 2, 2, 2, 4, 2, 1, 4, etc.
    Can you please tell me how to do this in either Pages or Open office?
    Thanks

    Thank you for your reply but when I go to the top menu and insert a footnote or endnote the program does not give me the option of manually putting in a number. The number is put in automatically and I can only choose numbering that is continuous, restart with each section or restart with each page.
    I am using Page '09 version 4.3 (1048)
    Can you tell me what I am doing wrong or give me another suggestion?
    Thanks
    Steve

Maybe you are looking for