java - 将字符串添加到字符串数组的开头

标签 java

是否可以在不迭代整个数组的情况下将字符串添加到字符串数组的开头。

最佳答案

这样做的唯一方法是维护一个环形缓冲区。即你有一个计数器,它记住开始在哪里,你移动它而不是移动数组中的所有条目。这只适用于您重新定义“开始”的含义。

查看 ArrayDeque 的来源其中包含三个字段

   86       /**
   87        * The array in which the elements of the deque are stored.
   88        * The capacity of the deque is the length of this array, which is
   89        * always a power of two. The array is never allowed to become
   90        * full, except transiently within an addX method where it is
   91        * resized (see doubleCapacity) immediately upon becoming full,
   92        * thus avoiding head and tail wrapping around to equal each
   93        * other.  We also guarantee that all array cells not holding
   94        * deque elements are always null.
   95        */
   96       private transient E[] elements;
   97   
   98       /**
   99        * The index of the element at the head of the deque (which is the
  100        * element that would be removed by remove() or pop()); or an
  101        * arbitrary number equal to tail if the deque is empty.
  102        */
  103       private transient int head;
  104   
  105       /**
  106        * The index at which the next element would be added to the tail
  107        * of the deque (via addLast(E), add(E), or push(E)).
  108        */
  109       private transient int tail;

所以添加到开头就像这样

  224       public void addFirst(E e) {
  225           if (e == null)
  226               throw new NullPointerException();
  227           elements[head = (head - 1) & (elements.length - 1)] = e;
  228           if (head == tail)
  229               doubleCapacity();
  230       }


  312       /**
  313        * @throws NoSuchElementException {@inheritDoc}
  314        */
  315       public E getFirst() {
  316           E x = elements[head];
  317           if (x == null)
  318               throw new NoSuchElementException();
  319           return x;
  320       }

注意:它移动头部而不是移动数组中的所有元素。

关于java - 将字符串添加到字符串数组的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14256013/

相关文章:

java - 在 Java Applet 中生成/下载文档

java - 如何使用 systemd-run 运行子进程并等待其完成

java - 打印数组变量,而不是变量指针位置

java - 如何在Java中设置Oracle编码

java - TreeSet<Object> 允许多个相同类型的对象

java - 在java web应用程序中如何从客户端打印服务器文件

java - Firebase - 获取子项等于的所有键

Java 在 MimeMessage 消息中添加 header

java - Angular代码不会通过将id传递给JAVA(使用Spring)来删除json

java - struts2 2.3.20 ognl 允许静态方法访问