最有效的方式来连接两个对象数组

时间:2013-06-13 20:57:47

标签: java arrays performance object merge

这个目标就是它的全部内容:

public class Unit {

private String label;
NumberRow numberRow;

Unit(String label){
    this.label=label;
    numberRow = new NumberRow();
}

....

}

它包含一个标签名称和一个双精度数组(即NumberRow()) 另一个名为UnitRow的类是这些单元的数组:

public class UnitRow {

Unit[] unitArray;
private int elementsInArray;
Scanner in;


UnitRow(){
    unitArray = new Unit[Dataset.numberOfRecords];
    elementsInArray = 0;
}
......

}

然而,我将介绍另一个类:Leaf。它包含一个单元并实现集群接口:

public class Leaf implements Cluster {

private Unit unit;

Leaf(Unit unit){
    this.unit = unit;
}

    .......
public UnitRow getUnits() {
    UnitRow unitRow = new UnitRow();
    unitRow.addLabel(unit.getLabel());
    for (int x = 0; x < Dataset.numberOfVariables; x++){
        unitRow.addVar(unit.valueOnIndex(x));
    }
    return unitRow;
}

public boolean hasChildren() {
    return false;
}

}

它包含一个单元,在UnitRow函数中,只用一个单元创建一个新的UnitRow;即在创建类时创建的单元。 另一个名为Node的类(最后一个)也实现了集群接口:

public class Node implements Cluster{

private Cluster leftChild;
private Cluster rightChild;

Node(Cluster leftChild, Cluster rightChild){
    this.leftChild = leftChild;
    this.rightChild = rightChild;
}

public UnitRow getUnits() {
    return leftChild.getUnits() + rightChild.getUnits();
}

}

节点有一个左子节点和一个右子节点。这样的孩子可以是叶子或其他节点。 现在我在Node中有一个函数给我一个来自下面所有叶子的单元数组。 我试着告诉java:return leftChild.getUnits()+ rightChild.getUnits();所以例如如果leftChild和rightChild都是leafs,那么它们将返回的数组将在该语句中添加到一起。但是,这不是正确的方法。让节点中的函数getUnits以最有效的方式返回一个包含Unit的数组的最有效方法是什么?

1 个答案:

答案 0 :(得分:1)

合并两个数组:

public UnitRow getUnits() {
    Unit[] array1and2 = new int[leftChild.getUnits().length + rightChild.getUnits().length];
    System.arraycopy(leftChild.getUnits(), 0, array1and2, 0, leftChild.getUnits().length);
    System.arraycopy(rightChild.getUnits(), 0, array1and2, leftChild.getUnits().length, rightChild.getUnits().length);
    return new UnitRow(array1and2); //add this constructor
}

或者,循环方式:

public UnitRow getUnits() {
    Unit[] array1and2 = new int[leftChild.getUnits().length + rightChild.getUnits().length];

    for (int i=0; i<leftChild.getUnits().length; i++) {
        array1and2[i]= leftChild.getUnits()[i];
    }

    for (int i=0; i<rightChild.getUnits().length; i++) {
        array1and2[leftChild.getUnits().length + i]= rightChild.getUnits()[i];
    }

    return new UnitRow(array1and2); //add this constructor
}