vikiv
vikiv

Reputation: 151

ArrayList overwriting itself

I've encountered a problem while trying to create an ArrayList of objects Frame. In a cycle, I always create an ArrayList of Integers, and then use this command to add new Frame to ArrayList packetList.

packetList.add(new Frame(tempFrameList, size, count));

My problem is, that I always end up with an array with the correct amount of Frames, but each frame is exactly the same, containing values from last added Frame.

I don't think the problem is with how the file is read, because when I add println into the cycle, where I add elements to array, the values are correct.

Here is the code where I add elements to ArrayList:

public class OpenFile {
        static Pcap pcap;
        static PcapPacket packet = new PcapPacket(JMemory.POINTER);
        static List<Frame> packetList = new ArrayList<Frame>();

    public void init(){
        final StringBuilder errbuf = new StringBuilder(); // For any error msgs
        final String file = "trace-1.pcap";
        int count = 0;
        int size;
        List<Integer> tempFrameList;

        pcap = Pcap.openOffline(file, errbuf);

    while (pcap.nextEx(packet) == Pcap.NEXT_EX_OK) {
        tempFrameList = new ArrayList<Integer>();
        count++;
        size = packet.size();

            for (int i = 0; i < size; i++) {
                tempFrameList.add(packet.getUByte(i));
            }

            //here is my problem
            packetList.add(new Frame(tempFrameList, size, count));
        }

        pcap.close();
    }
}

Here is the code from class Frame:

 public class Frame{
    private static List<Integer> frame = new ArrayList<Integer>();
    private static int size;
    private static int serialNum;


    public Frame(List<Integer> data, int newSize, int num) {
        Frame.frame = data;
        Frame.size = newSize;
        Frame.serialNum = num;
    }
}

Upvotes: 1

Views: 252

Answers (1)

Eran
Eran

Reputation: 393831

Here is your problem :

public class Frame{
  private static List<Integer> frame = new ArrayList<Integer>();
  private static int size;
  private static int serialNum;

The members of Frame shouldn't be static, since static members are shared across all instances of the class. Remove the static keyword.

Also change the constructor accordingly :

public class Frame {
    private List<Integer> frame = new ArrayList<Integer>();
    private int size;
    private int serialNum;


    public Frame(List<Integer> data, int newSize, int num) {
        this.frame = data;
        thus.size = newSize;
        this.serialNum = num;
    }
}

Upvotes: 6

Related Questions