亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 System.out.write 方法將 int 轉換為字節數組并打印到控制臺

使用 System.out.write 方法將 int 轉換為字節數組并打印到控制臺

胡子哥哥 2022-05-20 18:32:01
我有這個程序:public class Duplicates {    public static void main(String[] args) {        byte[] bytes = "hz".getBytes();        for (int i = 0; i < 10_000_000; i++) {            System.out.write(bytes, 0, bytes.length);        }    }}開始后我有輸出:hzhzhzhzhzhzhzhz .....hz但是如果我嘗試轉換int 為字節數組并打?。簆ublic class Duplicates {    public static void main(String[] args) {        byte[] bytes = ByteBuffer.allocate(4).putInt(666).array();        for (int i = 0; i < 10_000_000; i++) {            System.out.write(bytes, 0, bytes.length);        }    }}開始后我有輸出:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?入我想666在控制臺的每一行打印 10,000,000 次,并且使用的內存不超過 20MB 或 1 秒。我究竟做錯了什么?編輯如果我將使用示例@Justin -Integer.toString(i).getBytes()我有這個:
查看完整描述

2 回答

?
縹緲止盈

TA貢獻2041條經驗 獲得超4個贊

您面臨的問題不是調用,Integer.valueOf(666).toString()因為它只執行一次。實際的問題是,調用System.out.write()有一些開銷。這可以通過使用填充了一些重復輸入值的更大緩沖區來避免。


這是我想出的:


long start = System.currentTimeMillis();

byte[] bytes = String.valueOf(666).getBytes();


// use 20 mb of memory for the output buffer

int size = 20 * 1000 * 1000  / bytes.length;



byte[] outBuffer = new byte[size * bytes.length];

// fill the buffer which is used for System.out.write()

for (int i = 0; i < size; i++) {

    System.arraycopy(bytes, 0, outBuffer, i * bytes.length, bytes.length);

}


// perform the actual writing with the larger buffer

int times = 10_000_000 / size;

for (int i = 0; i < times; i++) {

    System.out.write(outBuffer, 0, outBuffer.length);

}

long end = System.currentTimeMillis();

System.out.println();

System.out.println("Took " + (end - start) + "Millis");

輸出 666 千萬次大約需要 600ms。


查看完整回答
反對 回復 2022-05-20
?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

這看起來是正確的。如果您將int666 轉換為 a char,則將顯示該內容。如果您想從字面上打印出 666,則需要將其轉換intString第一個:

byte[] bytes = Integer.toString(input).getBytes();


查看完整回答
反對 回復 2022-05-20
  • 2 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號