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

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

從左邊向數組添加新元素在java中向右移動一步

從左邊向數組添加新元素在java中向右移動一步

Helenr 2021-11-03 16:46:44
我的問題是:我希望向數組中添加一個元素。由于 'createArray' 方法方法 'addElementsToArray' 將新元素添加到 'this.array[0]' 的位置,數組長度為 3, 如果使用數組中的其余位置,則它們向右移動一步,使第一個位置為空對于新元素。如果我的數組長度等于 10 或 100 怎么辦?無論數組的長度如何,有沒有辦法使用更少的代碼行。謝謝private int[] array;public createArray(int m){    this.array = new int[m];}public void addElementsToArray(int element){        try {            for (int i=0; i<=this.getArray().length; i++) {                if (this.getArray()[i] == 0) {                    this.getArray()[i] = element;                    System.out.println("1");                    break;                }else if(this.getArray()[i] != 0 && this.getArray()[i + 1] == 0) {                    int vault = this.getArray()[i];                    if (this.getArray()[i + 1] == 0) {                        this.getArray()[i + 1] = vault;                        this.getArray()[i] = element;                        System.out.println("2");                        break;                    }                }else if(this.getArray()[i] != 0 && this.getArray()[i + 1] != 0) {                    if (this.getArray()[i + 2] == 0) {                        int vault = this.getArray()[i];                        this.getArray()[i + 2] = this.getArray()[i + 1];                        this.getArray()[i + 1] = vault;                        this.getArray()[i] = element;                        System.out.println("3");                        break;                    }                }            }        }catch(ArrayIndexOutOfBoundsException e){            System.out.println("This Stack is Full");        }    System.out.println(Arrays.toString(this.getArray()));}
查看完整描述

2 回答

?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

這個想法是從第一個元素到最后一個循環遍歷數組,尋找第一次出現的 0。如果沒有找到,則數組已滿。如果這樣做,請使用System.arraycopy將所有內容從 0 向右移動到標識的位置 1,然后在位置 0 處插入新元素。


public void addElementsToArray(int element){  

  for(int i=0; i<array.length; i++)

  {

    if(array[i] == 0)

    {

      System.arraycopy(array, 0, array, 1, i);

      array[0] = element;

      return;

    }

  }

  throw new IllegalStateException("Array is full");

}


查看完整回答
反對 回復 2021-11-03
?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

出于您的目的,數組不是用戶的最佳數據結構,而是使用隊列。


LinkedList<Integer> q = new LinkedList<>(); // LinkedList implements Queue interface

q.addFirst(5);        // will add element 5 at first position

q.addLast(6);        // will add element 6 at lastposition

int f = q.pollFirst();        // will give element at first position

int l = q.pollLast();        // will give element at lastposition


int ele= q.get(0);    // will give element at 0 index

Queue 用于在隊列末尾插入元素并從隊列開頭刪除元素。它遵循先進先出的概念。


查看完整回答
反對 回復 2021-11-03
  • 2 回答
  • 0 關注
  • 184 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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