簡體   English   中英

如何將元素添加到ArrayList

[英]How to add an element to an ArrayList

我如何使用戶輸入數字,然后將其向右移1.數組不能超過50。請幫助,在此先感謝:)

  List<Integer> list = new ArrayList<Integer>(1);
    public void add(int value) {

      list.add(0, value);
      for(int i = 0; i < array.length; i++) {
         list.add(index, value); // how to make the elements shift to the right?
         if(list.size > 50) {
           list.remove(50);
          }
       }
    }

ArrayList為您移動元素,這就是為什么它具有index的原因, 請看此答案

創建ArrayListnew ArrayList<Integer>(50) 50不定義size ,請定義ArrayList capacity 創建時為空,大小為0。

List<Integer> list = new ArrayList<Integer>(50);


public void add(int value) {
  if (list.size <= 50) list.remove(list.size() - 1);

  // inserting element at position 0 shifts other elements
  list.add(0, value);

}
 List<Integer> list = new ArrayList<Integer>(50);

  public void add(int value) {
     if (list.size() == 50)
         list.remove(list.size() -1);

     list.add(value);
  }
public class TestList {
   public static void main(String[] args) {

   ArrayList<Integer> arrlist = new ArrayList<Integer>(4);

   // use add() method to add elements in the list
   arrlist.add(15);
   arrlist.add(4);
   arrlist.add(5);

   // adding element 25 at third position
   arrlist.add(2,25);

   for (Integer number : arrlist) {
   System.out.println("List Value = " + number);
   }  
   }
}

將指定的元素插入此列表中的指定位置。 將當前在該位置的元素(如果有)和任何后續元素右移(將其索引添加一個)。 從這個“ http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

因此,您只需要檢查列表的大小是否不超過50,然后在指定的索引中添加數字即可。

List<Integer> list = new ArrayList<Integer>(50);

  public void add(int value) {

     if (list.size() == 50) // if the size of the array is 50, then remove the last value.
     list.remove(list.size() -1);

     list.add(int index, E element);// you can even choose where position to insert your value.
  }

在構造器部分中,您定義的是容量。 默認的最小容量為10。您知道您的數組不能超過50。有一個可能必須少於50的元素。因此,請首先將該構造器部分保留為空。

List<Integer> list = new ArrayList<Integer>();
    public void add(int value) {
        if(list.size() <50)
            list.add(0,value);
            else
            {
                list.remove(list.size()-1);
                list.add(0, value);
            }
private List<Integer> list = new ArrayList<Integer>(51);

public void add(int value) {
  list.add(0, value); //other elements are shifted right, you need do nothing else

  //then limit the list to 50 elements
  while(list.size() > 50) list.remove(list.size() - 1);
}

我看不到其余的代碼。 我不知道add之前列表的長度是多少,所以我只是保證一段while后它的長度是<= 50

您可以指定初始容量,如果可以的話,請使用51而不是50 它使數組的初始大小可以容納您的50 ,再加上列表中的51st會在移除前很短的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM