Search code examples
javaarraylistdata-structuresarraydeque

Which Java structure better to use? I need good performance, non-fixed size, and ease to clone / copy


I'd like to have a data structure with a good performance which allows easy clone/copy from one structure to another. My flow looks like this:

  • Take list1, full of objects.
  • Iterate over the objects, create from each object several objects of the same type, and add them into list2.
  • Erase all objects from list1 and add all objects from list2 into list1.
  • Erase all objects from list2.

I'm stuck to choose a data structure, for the moment I use ArrayDeque, which is not very fast. The number of objects is not fixed, so maybe array is not a good choice. Any advice please? Here is my code :

ArrayDeque<Obj> list1 = new ArrayDeque(),
list2 = new ArrayDeque();

// Iterate over list1 
// and add() objects into list2 

list1 = list2.clone();
list2.clear();

Thank you !


Solution

  • With 1000 objects you don't have to be too sophisticated unless this is performance critical or creation of each object of class Obj is a long process.

    Assuming following (very noddy) immutable Obj class:

    public static final class Obj {
        private String property;
    
        public Obj(String property) {
            this.property = property;
        }
    
        public String getProperty() {
            return property;
        }
    
        public Obj modify(String newProperty) {
            return new Obj(property + newProperty);
        }
    }
    

    Following code executes very quickly for 100k elements:

    public static final int NUM_ELEMENTS = 100_000;
    
    public static void main(String[] args) {
        //init
        ArrayDeque<Obj> source = new ArrayDeque<>(NUM_ELEMENTS);
        ArrayDeque<Obj> destination = new ArrayDeque<>(NUM_ELEMENTS);
    
        for(int i = 0; i < NUM_ELEMENTS; i++) {
            source.add(new Obj("" + i));
        }
    
        //modify
        source.stream()
                .map(obj -> obj.modify(" V2"))
                .forEach(obj -> destination.add(obj));
    
        source.clear();
    
        //print
        destination.stream()
                .forEach(obj -> System.out.println(obj.getProperty()));
    }