Results 1 to 2 of 2
  1. #1
    Rocketz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default Creating Objects within While Loops

    I'm trying to get UDP packets and store them in an ArrayList<DatagramPacket> within a while loop. However I feel like I'm adding a reference to a packet so that every object in the array just points to the last packet received. Here's what I'm working with:


    DatagramPacket receivedPacket = null;

    While (!finished) {
    receivedPacket = new DatagramPacket(buf, buf.length);
    socket.receive(receivedPacket); //socket is a DatagramSocket and this method changes the buffer within receivedPacket to contain the correct data from the current incoming packet.
    packets.add(receivedPacket); //packets is an ArrayList<DatagramPacket>
    }

    When I then try to use the DatagramPackets that should be in the array, they're all the same. I check using syso's to make sure they're not the same before they're added.

    I feel like an idiot that I can't figure this out after years of Java. Please help me.

  2. #2
    Rocketz is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default Re: Creating Objects within While Loops

    My problem is that all instances of receivedPacket pointed to the same buffer which was created outside the while loop. Please close this thread.

Similar Threads

  1. Creating files using loops
    By lakshmibvaraprasad in forum New To Java
    Replies: 2
    Last Post: 06-07-2011, 06:09 PM
  2. HELP - Creating OPTIONS in program and LOOPS
    By whateverme in forum New To Java
    Replies: 14
    Last Post: 12-07-2010, 06:55 AM
  3. creating dynamic objects?
    By alacn in forum New To Java
    Replies: 4
    Last Post: 06-04-2010, 04:51 AM
  4. Creating an array of objects
    By geowizard in forum New To Java
    Replies: 5
    Last Post: 11-16-2009, 02:25 AM
  5. Replies: 2
    Last Post: 02-23-2009, 03:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •