Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get/Set from C# to Java [closed]

Tags:

java

c#

set

get

I'm working on a project to translate a c# project to Java. I have the following Get/Set block in C#

 public Unit[] Units
{
    get
    {
        Unit[] units_aux = new Unit[this.list_units.Count];
        this.list_units.CopyTo(units_aux);
        return units_aux;
    }
    set
    {
        if (value == null) return;
        Unit[] units_aux = (Unit[])value;
        this.list_units.Clear();
        foreach (Unit u in units_aux)
            this.lista_units.Add(u);
    }
}

I want to translate this to Java, but I have not been successful in translating it with no syntax errors. I'm very new to Java, so maybe this is a basic question, but i haven't found any information on how to do this that won't produce errors.

Thanks for your help

like image 228
Ichigo-San Avatar asked Dec 20 '22 11:12

Ichigo-San


1 Answers

You'd basically have to convert it to a pair of methods:

public Unit[] getUnits() {
    // Method body
}

public void setUnits(Unit[] value) {
    // Method body
}

Java doesn't have properties at a language level - the above is basically just a (very common) convention.

I should note, by the way, that this C# code really isn't terribly nice:

  • There are simpler ways of converting an array to a list and vice versa
  • The setter ignores a null value when I'd expect it to throw an exception
  • By cloning the array, it doesn't have the generally-expected behaviour (at least, my expectations) if you set the property and then modify the array contents. It's usually a bad idea to have an array as a property type anyway; if you could get away with making it a read-only collection, that would be nicer and make life much simpler.
like image 199
Jon Skeet Avatar answered Dec 29 '22 02:12

Jon Skeet