Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Everyone, I am doing an assignment in java. I am making use of Collections.copy method available in Collections class. Following is a snippet of my code.



XML
public Queue(List<E> queue1) {
        queue = new ArrayList<E>(queue1.size());
        System.out.println("const" + queue1.size());
//      Collections.copy(this.queue, queue1);
        this.queue = queue1;
    }

The problem is when I'm using Collections.copy method its throwing me a NullPointerException, I don't know why? When I'm assigning directly using '=', it's working fine. Following is the snippet of code, where I am invoking this construcor.

XML
List<Integer> e = new ArrayList<Integer>(3);
        e.add(1);
        e.add(2);
        e.add(3);
        System.out.println(e.size());
        Queue<Integer> p = new Queue<Integer>(e);

Anyone knows how to solve it, please help me out. I need to use collections.copy here.
Thanks and regards,
Vinay Kumar Tiwary
Posted
Updated 16-Nov-13 16:07pm
v2
Comments
CHill60 16-Nov-13 15:49pm    
how have you defined the property "queue" in the Queue class? this.queue must have at least the same capacity as queue1, and of course you must have created an instance of queue.
Note this.queue = queue1 is not actually making a copy of the ArrayList - both are pointing to the same data in memory.
Vinay Kumar Tiwary 16-Nov-13 22:09pm    
Hey, thanks for reply.. I did forget to initialize it..:P Sorry.. Now u can see, I've initailized it with the same size of queue1. Now its throwing me ArrayIndexOutOfBoundsException. Please help me out.
Richard MacCutchan 17-Nov-13 6:13am    
You need to provide more information; exactly where does the error occur, and what are the values of the variables.
Vinay Kumar Tiwary 17-Nov-13 7:06am    
Thanks for looking into this.. I got d solution. my initialization was wrong. Actually I'm a newbie to collections classes. To initialize the new list, I just passed the old list as argument to constructor and its working fine now.
Thanks everyone. :) :) :)

1 solution

Initialize the new list with existing list by adding as an argument to the constructor as follows. It works fine. :)
XML
public Queue(List<E> queue1) {
        queue = new ArrayList<E>(queue1);
        Collections.copy(this.queue, queue1);
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900