HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

A more efficient enqueue algorithm in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
moreefficientjavaalgorithmenqueue

Problem

So I have this simple code in Java. It enqueue (adds) and element to the end of the queue (implemented by an ArrayList) without changing the original queue.

public class MyQueue{
    private List body;

    // some constructors and helper functions.

    //copy constructor
    public MyQueue(List list){
        this.body = list;
    }

    //this is the function
    public MyQueue enqueue(T obj){
        List temp = new ArrayList(body);
        temp.add(obj);
        return new Queue(temp);
    }


The whole idea is to make enqueue faster and more efficient, and again, as you notice, without changing the value of the original queue. Any ideas?

UPDATE
For the sake of completing the idea.

1- This is an assignment so university, the skeleton provided is not to be changed, the task is to make the function enqueue faster (i do realize i am copying twice and thats the slow part).

2- As for the helper functions, they are simple:

public T peek(){
if(body.isEmpty()){
   thrown new NoSuchElementException();
}
return body.get(0);
}

public int size(){
return body.size();
}

Solution

It seems like what you are trying to accomplish here is to make your Queue class immutable. That in itself is good, but there are a couple of issues with your approach:

  • Creating a new class for this is not needed. There already exists classes for that. Use Collections.unmodifiableList to create one.



  • Your class does not implement the List interface (or the Queue interface for that matter). I guess there is a way to access the embedded List such as getList hidden among "some constructors and helper functions", but if all that does is to return this.body; then your entire list is still accessible and modifiable.



  • The List body field could be, and should be, declared final.



Instead of your entire Queue class, you might want to use this static method:

public static  List addToList(List oldList, E newElement) {
    List temp = new ArrayList(oldList);
    temp.add(newElement);
    return Collections.unmodifiableList(temp);
}


I should add however, that there is a difference between an unmodifiable list and what I understood about your approach. An unmodifiable list in Java does not allow any change to the list at all, such as list.set(index, obj).

Code Snippets

public static <E> List<E> addToList(List<E> oldList, E newElement) {
    List<E> temp = new ArrayList<E>(oldList);
    temp.add(newElement);
    return Collections.unmodifiableList(temp);
}

Context

StackExchange Code Review Q#35485, answer score: 2

Revisions (0)

No revisions yet.