1

I need to return integer and byte array, I found that I can return them using Object[], but I'm not sure how to get integer and byte array.

It returns Object with integer and byte array:

public static Object[] readVarInt(DataInputStream in) throws IOException {
    int i = 0;
    int j = 0;
    byte[] byteArr = null;
    byte b = 0;
    while (true) {
        int k = in.readByte();
        i |= (k & 0x7F) << j++ * 7;
        if (j > 5) {
            throw new RuntimeException("VarInt too big");
        }
        if ((k & 0x80) != 128) {
            break;
        }
        byteArr = Arrays.copyOf(byteArr, b);
        byteArr[b] = (byte) k;
        b+=1;
    }
    return new Object[] {i, byteArr}; // <<---
}

I don't know how to get from Object[] my integer and byte array:

Object Object;
Object = Protocol.readVarInt(serv_input);
int intLength = Object[0]; // <<---
byte[] byteArray = Object[1]; // <<---

This won't work because it thinks it's array, but it's object...

(Sorry for my poor knowledge, I'm new in Java...)

Algirdas Butkus
  • 98
  • 1
  • 10

2 Answers2

3

You can use type casting to get data from Object[]

    int intLength = (int) result[0];
    byte[] byteArray = (byte[]) result[1];

But I would recommend to use wrapper object instead of Object[] as result of method:

class Result {
    private final int length;
    private final byte[] byteArr;

    Result(int length, byte[] byteArr) {
        this.length = length;
        this.byteArr = byteArr;
    }

    public int getLength() {
        return length;
    }

    public byte[] getByteArr() {
        return byteArr;
    }
}

public static Result  readVarInt(DataInputStream in) throws IOException {
    ...
    return new Result(i, byteArr);
}

....

Result result = readVarInt(serv_input);

int intLength = result.getLength();
byte[] byteArray = result.getByteArr();

Also be aware that this part byteArr = Arrays.copyOf(byteArr, b); returns NPE in first step of execution because you are trying to copy data from null.

Vlad Bochenin
  • 3,007
  • 1
  • 20
  • 33
1

What you could do would be to test if the object you are trying to access is of a specific class using instanceof and then explicitly cast your object.

if (test[0] instanceof Integer) {
  intLength = (Integer) test[0];
} 
if (test[0] instanceof byte[]) {
  byteArray = (byte[]) test[0];
}

However I would not recommend to do that because I tend not to store things in Object since you never know of which class they are.

Maybe you should try to store your data in a Map that takes the lenght you are calculating as the key and the byte array as the value.

Map<Integer, byte[]> result = new HashMap<>();
result.put(i, byteArray);

One thing to notice is that the key of the map cannot be an int but as to be an Integer.

Rlarroque
  • 1,900
  • 1
  • 17
  • 27