Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`*this = rhs` in Java?

Tags:

java

c++

I'm coming from the C++ world and I can't find what is the Java alternative (if any) to the following:

struct SomeStruct
{
    SomeStruct(){}
    SomeStruct(const SomeStruct& rhs)
    {
        *this = rhs;
    }
};

The reason why I need this is that I have a cache of existing objects, so I don't want to create another instance but just to 'clone' the existing one, something like this:

public class SomeObject
{
    private static Hashtable _objects;
    SomeObject()
    {
        SomeObject obj = _objects.get(some_key);
        if (obj != null) {
            // *this = obj;
            // instead of: 
            // this.something = obj.something;
            // this.something1 = obj.something1;
            // this.something2 = obj.something2;
            // a zillion fields....
        }
    }
};

EDIT:

Sorry, I confused some things (still need to learn both Java and C++).

Thank You

like image 376
HotHead Avatar asked Feb 21 '11 16:02

HotHead


People also ask

What does RHS stand for Java?

The compiler doesn't know that rhs stands for "right hand side", and in fact the name of that variable can be anything you like. The compiler "knows" how to format this because the syntax of operator= requires it to be this way. class A { public: A& operator=(const A& other); };

What is RHS in coding?

lhs refers to “left hand side”, indicating it is on the left side of the = operator, and rhs refers to the “right hand side”, similarly indicating that it is on the right of the = operator.


1 Answers

The closest is Object.clone() but read the relevant section from Effective Java first.

There are probably simpler ways to do what you want if you remove some of your requirements. For example, if you make your objects immutable then you don't need to copy the data into another object. Instead you can return a reference to the original object. This is much faster than a memberwise copy, and has lots of other benefits too, such as making it easier to write thread-safe code.

like image 126
Mark Byers Avatar answered Oct 15 '22 15:10

Mark Byers