Java 数组的setter和getter

Java 数组的setter和getter,java,arrays,Java,Arrays,我是Java新手,需要澄清如何处理问题 我有一类本轮,定义如下: public class Ts_epicycle { private double epoch; private double[] tle = new double[10]; } 在另一个类中,Refine我正在调用一个需要tle数组的方法: // create an instance of Epicycle Epicycle e = new Epicycle(); methodExample(keps1, k

我是Java新手,需要澄清如何处理问题

我有一类本轮,定义如下:

public class Ts_epicycle {
    private double epoch;
    private double[] tle = new double[10];
}
在另一个类中,
Refine
我正在调用一个需要
tle
数组的方法:

// create an instance of Epicycle
Epicycle e = new Epicycle();

methodExample(keps1, keps2, e.tle);
在methodExample中,我将设置
tle

1) 为
tle
数组创建getter/setter的最佳方法是什么?(对于另一个变量也是如此)

2) 在methodExample中,我需要传入整个
tle
数组的参数,而不是它的任何特定索引。我该怎么办呢


如果我没有说清楚,请道歉。

如果您只允许用户一次编辑一个数组,则可以将
synchronized
关键字添加到方法签名中。访问阵列已经是线程安全的,因此不需要任何东西

例如:

double getTle(int index) {
    return tle[index]
}

synchronized void setTle(int index, double value) {
    tle[index] = value;
}

这只允许一次调用该方法一次

事实上,这是一个有趣的问题:

为了使更改获取数组中的条目不会更改原始对象, 您需要返回数组的副本。不太好

或者,您可以使用List类而不是数组:

public class TsEpicycle {
    private double epoch;
    private List<Double> tle = new ArrayList<>();

    public List<Double> getTLE() {
        return Collections.unmodifiableList(tle);
    }
}

您的数组是一个与java中的任何其他对象类似的对象。

// to declare and initialize your array

private int[] st = new int[10];

//getter and setter 

public int[] getSt() {
        return st;
    }
public void setSt(int[] st) {
        this.st = st;
    }

//for the last method u can use 

public void method(int value)
{
for(int i = 0 ; i<st.lenght ; i++){
st[i] += value; // for exemple
}
//声明和初始化数组
私有整数[]st=新整数[10];
//接二连三
公共int[]getSt(){
返回st;
}
公共无效设置(int[]st){
this.st=st;
}
//最后一种方法你可以用
公共void方法(int值)
{

对于(inti=0;i作为一般最佳实践,类中需要从另一个类访问的每个字段都应该提供一个getter和一个setter(如果对象是可变的)


正如Joop Eggen在其回答中所解释的那样,通常返回副本或代理(例如引用数组的列表/集合)是一种很好的做法为了保持原始数组的状态,

TLE已经是线程安全的,因为它是一个非静态变量,并且在您的函数中每次创建一个周转周期的实例,以防您计划将数组的引用提供给另一个线程,考虑使用读写锁。您还可以使用<代码> TLE。
对于不需要导入java.util.Arrays的数组副本来说,@Leponzo是正确的,这也消除了长度参数。我避免克隆(与类相关),但在数组上没有理由。
public class TsEpicycle {
    private double epoch;
    private double[] tle = new double[10];

    public DoubleStream getTLE() {
        return Stream.of(tle);
    }
}
// to declare and initialize your array

private int[] st = new int[10];

//getter and setter 

public int[] getSt() {
        return st;
    }
public void setSt(int[] st) {
        this.st = st;
    }

//for the last method u can use 

public void method(int value)
{
for(int i = 0 ; i<st.lenght ; i++){
st[i] += value; // for exemple
}