UnsupportedOperationException on ByteBuffer.asCharArray().array()

独自空忆成欢 提交于 2020-01-24 10:40:30

问题


Could someone be so kind to explain why on the following line I have UnsupportedOperationException?

System.out.println(ByteBuffer.wrap(new byte[] {'t', 'e', 's', 't', '\n'}).asCharBuffer().array());


回答1:


The asCharBuffer doesn't wrap a char[] so you cannot obtain its array()

It appears what you are trying to do is.

System.out.println(Arrays.toString("test\n".toCharArray()));



回答2:


Did you read the Javadoc for CharBuffer.array()?

Not all CharBuffers are backed by a char[]. ByteBuffer.asCharBuffer() returns a view of the ByteBuffer as a CharBuffer, so its result is backed by a byte[].

array() only returns the char[] that actually backs the buffer, and if none exists, it throws a UOE. The closest alternative you'll be able to get is something like

char[] result = new char[charBuf.remaining()];
charBuf.get(result);


来源:https://stackoverflow.com/questions/11761700/unsupportedoperationexception-on-bytebuffer-aschararray-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!