类属性初始化与数组 - java

时间:2021-01-09 21:19:15

I would know a better way to initialize this kind of class:

我知道一种更好的方法来初始化这种类:

public class TestClass{
    private byte[] attribute0;
    private customClass0 attribute1;
    private customClass1 attribute2;
    ...

    public TestClass(byte[] args){
        int offset = 0;
        byte[] argsCustomClass0;
        byte[] argsCustomClass1;
        System.arraycopy(args, offset, attribute0, 0, attribute0.length);
        offset += attribute0.length;
        System.arraycopy(args, offset, argsCustomClass0, 0, argsCustomClass0.length);
        offset += attribute0.length;
        attribute1 = new CustomClass1(argsCustomClass0);
        System.arraycopy(args, offset, argsCustomClass1, 0, argsCustomClass1.length);
        offset += argsCustomClass1.length;
        attribute2 = new customClass1(argsCustomClass1);
        ...
    }

This is working but it's pretty "dirty coding", does anyone knows another way to initialize these attributes using an array? I precise that my args array could be very large an my attributes number as well.

这是有效的,但它非常“脏编码”,有没有人知道使用数组初始化这些属性的另一种方法?我确切地认为我的args数组可能非常大,也是我的属性数。

Thanks!

Flo

1 个解决方案

#1


3  

Use an array of arrays:

使用数组数组:

public class TestClass{
    private byte[][] attributes;
    // -----^^^^^^^^

    public TestClass(byte[] args){
        int offset = 0;
        for (byte[] a : attributes) {
            System.arraycopy(args, offset, a, 0, a.length);
            offset += a.length;
        }
    }

#1


3  

Use an array of arrays:

使用数组数组:

public class TestClass{
    private byte[][] attributes;
    // -----^^^^^^^^

    public TestClass(byte[] args){
        int offset = 0;
        for (byte[] a : attributes) {
            System.arraycopy(args, offset, a, 0, a.length);
            offset += a.length;
        }
    }