How to efficiently concatenate data of two vectors in java me?

I have two vectors in my program and I want to join their data

Vector a=new Vector();
Vector b=new Vector();

      

+3


source to share


2 answers


Vector a = new Vector();
Vector b = new Vector();

// populate vectors a and b
// ...

Vector c = new Vector();

for(Enumeration e = a.elements(); e.hasMoreElements();) {
    c.addElement(e.nextElement());
}
for(Enumeration e = b.elements(); e.hasMoreElements();) {
    c.addElement(e.nextElement());
}

// c now contains all elements from a followed by all elements from b

      



+4


source


It's safe and enjoyable. If you're a bit of a performance freak, you can also try a lower-level solution. By subclassing a Vector, you access the Vector's fields so that you can:



NakedVector a = new NakeVector();
NakedVector b = new NakeVector();

// populate a, b 

NakedVector c = new NakedVector(a, b);

class NakedVector extends Vector {

    public NakedVector() {
        super();
    }

    ...

    public NakedVector(NakedVector a, NakedVector b) {
        elementData = new Object[a.size() + b.size()]; // or: super(a.size() + b.size());
        elementCount = elementData.length;
        System.arraycopy(a.elementData, 0, elementData, 0, a.size());
        System.arraycopy(b.elementData, 0, elementData, a.size(), b.size());
    }
}

      

+1


source







All Articles