2017-02-02 41 views
1

我需要返回整數和字節數組,我發現我可以使用Object []返回它們,但我不知道如何獲取整數和字節數組。在Java中的返回對象[]

它返回的對象與整數,字節數組:

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}; // <<--- 
} 

我不知道如何從Object []我的整數,字節數組得到:

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

這不會工作,因爲它認爲它的陣列,但它的對象...

(對不起,我的新知識,Java ...)

+1

您的(非工作)示例代碼會調用'readVarInt()'兩次,這會導致從'serv_input'讀取兩次,大概是不同的值。這是打算? –

+0

這只是一個例子。我會解決這個問題。 –

+0

@Shashwat是的,沒錯。 –

回答

3

您可以使用類型轉換,從Object[]

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

獲取數據,但我會建議使用包裝對象,而不是Object[]作爲方法的結果是:

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(); 

另外要注意,這部分byteArr = Arrays.copyOf(byteArr, b);在執行的第一步中返回NPE,因爲您試圖從null複製數據。

+0

非常感謝。問題解決了! –

1

你可以做的是測試你試圖訪問的對象是否是使用instanceof的特定類,然後明確地轉換你的對象。

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

不過,我不會建議這樣做,因爲我往往不存儲對象的事情,因爲你永遠不知道他們是哪個班。

也許你應該嘗試將你的數據存儲在一個Map中,它將你計算的長度作爲關鍵字,字節數組作爲值。

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

有一點要注意的是,地圖的鍵不能是int,但作爲爲整數。