Thắc mắc về Java Collection và Wrapped class trong Java

Trước khi hỏi thì mình gửi lời cảm ơn đến các bạn trước.
Vấn đề là Mình đang gặp vấn đề ở lớp Wrapped trong quá trình sử dụng Java Collection
Khi mình truyền mảng String vào method Arrays.asList thì không bị lỗi gì nhưng khi truyền mảng char vào thì bị báo lỗi, dù đã dùng wrapped class chuyển char qua Character

1 Like

Do you know the difference between char and Character? It’s similar to int and Integer, double and Double. The Arrays.aslist cannot convert a char array to Character list. But it works if you do as following

List<Character> charList = Arrays.asList('A', 'B', 'C', 'D');

why? because as a single value ‘A’ there is a swap to the Character object, but an array of char cannot become a single char for each Character object, but only as a List<char[]>

1 Like

When I convert char[] to Character in line 10, there is no more error.

1 Like

because Character is a Java object while char is a primitive. Because List< E > requires E as an object and Arrays.asList() does not perform the conversion from primitive (char) to object (Character) so you get an error. That is why you convert a Char array to a Character array and you do not get an error. It is similar to a String array or Integer/Double/Byte/Short/Float/Character array

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?