【问题标题】:Most efficient way to join two object arrays连接两个对象数组的最有效方法
【发布时间】:2013-06-10 10:07:48
【问题描述】:

这个对象就是它的全部:

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;
}

}

它包含一个 Unit,在函数 UnitRow 中创建一个新的 UnitRow,其中只有一个 Unit;即创建类时给出的单位。 另一个名为 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 都是叶子,则它们将返回的那些数组在该语句中相加。然而,这不是正确的方法。让Node中的函数getUnits以最有效的方式返回一个带有Units的数组的最有效方法是什么?

【问题讨论】:

  • 考虑改用Lists(例如ArrayList)。使用List,您可以致电addAll
  • 我希望我可以,但大学不会让我这样做...

标签: java arrays performance object merge


【解决方案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
}

【讨论】:

  • 是的,这当然是一个很好的解决方案,但是您为它通过的每个节点创建一个新数组。有必要吗?
猜你喜欢
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多