数组的setter和getter [英] Setters and getters for arrays

查看:99
本文介绍了数组的setter和getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,我需要澄清如何解决问题.

I am new to Java and I need some clarification how to approach an issue.

我有一个类 Epicycle ,定义如下:

I have a class Epicycle, defined below:

public class Ts_epicycle {
    private double epoch;
    private double[] tle = new double[10];
}

在另一个类中, Refine 我正在调用一个需要 tle 数组的方法:

In another class, Refine I am calling a method that requires the tle array:

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

methodExample(keps1, keps2, e.tle);

在methodExample中,我将为 tle

In methodExample, I would be setting the array values for tle

1)为 tle 数组创建getter/setter的最佳方法是什么?(以及其他变量).

1) What is best way for creating getters/setters for the tle array? (and for the other variable too).

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

2) In the methodExample, I need to pass in the argument for the whole tle array rather than any particular index of it. How would I go about this.

很抱歉,如果我不清楚的话.

Apologies if i'm not making it clear.

推荐答案

实际上是一个有趣的问题:

In fact an interesting question:

为了更改获得的数组中的条目不会更改原始对象,您将需要返回该数组的副本.不太好.

In order that altering entries in the gotten array does not alter the original object, you would need to return a copy of the array. Not so nice.

public class TsEpicycle {
    private double epoch;
    private double[] tle = new double[10];

    public double[] getTLE() {
        return Arrays.copyOf(tle, tle.length);
    }
}

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

Alternatively you could use the List class instead of an array:

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

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

这不会产生副本,但是简单地不允许在运行时更改列表.这里的效率低下是因为Double对象包装了double.

This does not make a copy, but simple disallows at run-time to alter the list. Here the inefficiency is in the Double objects wrapping doubles.

最好是使用新的Stream类:遍历双打:

The best might be to use the new Stream class: for iterating through the doubles:

public class TsEpicycle {
    private double epoch;
    private double[] tle = new double[10];

    public DoubleStream getTLE() {
        return Stream.of(tle);
    }
}

这篇关于数组的setter和getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆