| |

VerySource

 Forgot password?
 Register
Search
View: 718|Reply: 4

Why is an exception thrown here?

[Copy link]

3

Threads

17

Posts

14.00

Credits

Newbie

Rank: 1

Credits
14.00

 China

Post time: 2020-1-15 17:20:01
| Show all posts |Read mode
import java.nio. *;
// import java.util. *;

public class UsingBuffers
{
public static void changePos (CharBuffer cb)
{
while (cb.hasRemaining ())
{
cb.mark ();
char c1 = cb.get ();
char c2 = cb.get ();
cb.reset ();
cb.put (c2) .put (c1);
}
}
public static void main (String [] args)
{
// ByteBuffer buf = ByteBuffer.allocate (1024);
CharBuffer cb = CharBuffer.wrap ("ababab");
//cb.put("ababab ");
changePos ((CharBuffer) cb.rewind ());
System.out.println ((CharBuffer) cb.rewind ());
}
}
Calling the static method will throw an exception, not calling it will not, what is going on?
Reply

Use magic Report

1

Threads

20

Posts

15.00

Credits

Newbie

Rank: 1

Credits
15.00

 China

Post time: 2020-1-22 19:27:02
| Show all posts
Because the incoming CharBuffer is ReadOnly, it cannot be put
Reply

Use magic Report

3

Threads

17

Posts

14.00

Credits

Newbie

Rank: 1

Credits
14.00

 China

 Author| Post time: 2020-1-22 22:00:02
| Show all posts
So why is this possible?
ByteBuffer buf = ByteBuffer.allocate (1024);
CharBuffer cb = buf.asCharBuffer ();
cb.put ("fsdfd");
Passing cb to the function will not throw an exception. . . .
Reply

Use magic Report

3

Threads

17

Posts

14.00

Credits

Newbie

Rank: 1

Credits
14.00

 China

 Author| Post time: 2020-1-22 22:09:01
| Show all posts
Help yourself
Reply

Use magic Report

1

Threads

20

Posts

15.00

Credits

Newbie

Rank: 1

Credits
15.00

 China

Post time: 2020-1-22 23:36:01
| Show all posts
asCharBuffer
public abstract CharBuffer asCharBuffer ()
Creates a view of this byte buffer as a char buffer.
The content of the new buffer will start at this buffer's current position. Changes to this buffer's content will be visible in the new buffer, and vice versa; the two buffers' position, limit, and mark values ​​will be independent.

The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided by two, and its mark will be undefined. The new buffer will be direct if, and only if, this buffer is direct , and it will be read-only if, and only if, this buffer is read-only.


Returns:
A new char buffer

See the last sentence: and it will be read-only if, and only if, this buffer is read-only.
From this point of view, ByteBuffer buf = ByteBuffer.allocate (1024) applied for this way;
ByteBuffer is writeable
lz can be reviewed with this method
isReadOnly ()
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list