2012-02-16 26 views
2

我完全難倒..好像有會成爲一個簡單的解決方案無法分配的getBytes()以字節數組

private Byte[] arrayOfBytes = null;  

public Data(String input) { 
    arrayOfBytes = new Byte[input.getBytes().length]; 
    arrayOfBytes = input.getBytes(); 
} 

拋出follwing錯誤:從字符串

incompatible types 
    required: java.lang.Byte[] 
    found: byte[] 
+1

自動裝箱只是處理值的轉換不是類型轉換 – Kennet 2012-02-16 19:24:31

回答

4

getBytes()返回byte[],並且您試圖將其影響到Byte[]

byte是原始的,而Byte是一個包裝類(有點像Integer和int)。

你可以做的就是變化:

private Byte[] arrayOfBytes = null; 

到:

private byte[] arrayOfBytes = null; 
+0

這肯定將清除的東西了,謝謝你 – Marshma11ow 2012-02-16 19:20:11

+0

@marshmallow不客氣。 – talnicolas 2012-02-16 19:21:29

2

所以嘗試:

private byte[] arrayOfBytes = null;  

public Data(String input) { 
    arrayOfBytes = new byte[input.getBytes().length]; 
    arrayOfBytes = input.getBytes(); 
} 
+0

感謝您的快速響應!但是,這不正是我寫的,排隊嗎? – Marshma11ow 2012-02-16 19:19:46

+0

@marshmallow:將'Byte'改爲'byte'。 – RanRag 2012-02-16 19:20:32

+1

我現在看到它,謝謝。字節是一個對象,字節是原始的。 – Marshma11ow 2012-02-16 19:24:39

2

字節是一個對象,而字節是靈長類動物。就像Integer和int之間的區別一樣。

+0

好比喻,謝謝我現在明白了 – Marshma11ow 2012-02-16 19:20:54

1

getBytes()返回一個byte[]數組。您正在分配到Byte[]陣列。

所以,這應該工作

private byte[] arrayOfBytes = null;  

public Data(String input) { 
    arrayOfBytes = new Byte[input.getBytes().length]; 
    arrayOfBytes = input.getBytes(); 
} 

The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.

1
public Data(String input) { 
    arrayOfBytes = new byte[input.getBytes().length];// this line is useless 
    arrayOfBytes = input.getBytes(); 
} 
+0

尷尬,謝謝你的擡頭 – Marshma11ow 2012-02-16 19:22:17

相關問題