【问题标题】:Java - Unordered List methods for ArrayList?Java - ArrayList 的无序列表方法?
【发布时间】:2017-09-21 02:47:38
【问题描述】:

我想知道 ArrayList 的 UnorderedList 的方法是什么样的。我知道我们会有 addToFront、addToRear 和 addAfter(都带有 T 元素),但我只见过用数组实现的(见下文)。是否可以使用 ArrayList 代替?这将如何改变方法?希望我的问题有意义。

这是我遇到的代码:

public void addToFront(T element) {

    if (size() == list.length) {
        expandCapacity();
    }

    for (int i = this.size(); i > 0; i--) {
        this.list[i] = this.list[i-1];
    }

    this.list[0] = element;
    this.rear++;
}

/**
 * Adds the specified element to the rear of this list.
 *
 * @param element  the element to be added to the list
 */
public void addToRear(T element) {
    if (size() == list.length) {
        expandCapacity();
    }

    this.list[rear] = element;
    this.rear++;
}

/**
 * Adds the specified element after the specified target element.
 * Throws an ElementNotFoundException if the target is not found.
 *
 * @param element  the element to be added after the target element
 * @param target   the target that the element is to be added after
 */
public void addAfter(T element, T target) {
    if (size() == list.length) {
        expandCapacity();
    }

    int scan = 0;
    while (scan < rear && !target.equals(list[scan])) {
        scan++;
    }

    if (scan == rear) {
        throw new ElementNotFoundException("list");
    }

    scan++;
    for (int scan2 = rear; scan2 > scan; scan2--) {
        list[scan2] = list[scan2 - 1];
    }

    list[scan] = element;
    rear++;
}
}

【问题讨论】:

  • 不多。试一试。您的代码中使用的一些内置表示可能会更改。
  • @nullpointer 在扩展容量方面,ArrayList 是否需要这样做?我的知识可能有限,但它的容量不是自动增长的吗?

标签: java list arraylist unordered


【解决方案1】:

ArrayList 抽象了过渡数组的大小管理方面。签出:

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(int,%20E)

import java.util.ArrayList;

public class Test<T> {
  ArrayList<T> yourArray;

  Test() {
    // Initialize to avoid NPEs
    yourArray = new ArrayList<T>();
  }

  public void addToFront(T element) {
    yourArray.add(0, element);
  }

  public void addToRear(T element) {
     yourArray.add(yourArray.size(), element);
  }

  public void addAfter(T element, T target) {
     yourArray.add(yourArray.indexOf(target) + 1, element);
  }

  public void addBefore(T element, T target) {
     final int location = yourArray.indexOf(target);

     if (location == 0) {
       addToFront(element);
     } else {
       yourArray.add(yourArray.indexOf(target) - 1, element);
     }
  }
}

【讨论】:

  • 你是对的。我想我应该复习一下我的 ArrayList 方法。我忘了它可以通过简单地将元素添加到第一个索引来将内容向右移动。
猜你喜欢
  • 2011-07-19
  • 2015-02-14
  • 1970-01-01
  • 2012-02-05
  • 2015-08-15
  • 1970-01-01
  • 2018-03-27
  • 1970-01-01
  • 2014-08-20
相关资源
最近更新 更多