0

I've been trying to write a method that takes an ArrayList as a parameter and returns the contents of this ArrayList in an object of the class TAG_Byte that I made for this purpose.

It does that by removing data it already got.

static  TAG_Byte DecodeByte(List<Byte> nbtfile) {
    nbtfile.remove(0);
    String Name = new String();
    for(int i=0;i<((nbtfile.get(0)<<8)+nbtfile.get(1));i++)
    {
        Name+=(char)(byte)nbtfile.get(2);
        nbtfile.remove(2);
    }
    
    nbtfile.remove(0);
    nbtfile.remove(0);
    TAG_Byte res = new TAG_Byte(Name);
    res.setPayLoad(nbtfile.get(0));
    
    return res;
}

In my main method, I'm running this function three times, getting different values every time, that I'm printing

Byte[] myarray = {0x01, 00, 05, 0x73, 0x63, 0x61, 0x6C, 0x65, 00};

ArrayList<Byte> mylist = new ArrayList<Byte>();
for(byte b: myarray)
{
    mylist.add(b);
}
System.out.println(NBTFile.DecodeByte(mylist).Name);
System.out.println(NBTFile.DecodeByte(mylist).getPayLoad());
System.out.println(NBTFile.DecodeByte(mylist).getId());

This works fine on the first iteration, but after that the ArrayList mylist only contains the last Byte for some reason, leading to a IndexOutOfBounds Exception. I've tried setting myList to final already, but that didn't help at all.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    You **are** calling remove on your input list. – akarnokd Jun 19 '22 at 11:06
  • An `ArrayList` is a modifiable collection. You pass the array list to your method and your method removes items from your list. If you don't want that, you need to copy the list before calling (or copy the list in the method). – Mark Rotteveel Jun 19 '22 at 11:08
  • Have you tried running your code in a debugger using single step? What did you observe? – schrom Jun 19 '22 at 11:08

0 Answers0