在java中创建最近使用的列表

时间:2016-01-29 20:52:55

标签: java netbeans

我有一个任务,我必须在java中创建一个最近使用的列表。我有点失落,我真的不知道从哪里开始。请帮忙!这是我开始使用的代码:

public class RecentlyUsedList {

    // Members (a.k.a. fields)
    private String[] theItems;
    private int noOfItems;

    // Constructor
    public RecentlyUsedList(int capacity) {
        // Create the array with indicated capacity
        // Initialize numberOfItems
    }

    // Public methods
    public int getNoOfItems() {


    }

    public boolean isEmpty() {
        // Is this list empty or not?
    }

    public String getItemAt(int index) {
        // If index is out of range, return null
        // Otherwise return a reference to the indicated item
    }

    public void addItem(String item) {
        // 1. Check if the list contains this item; if so, remove it and pack
        // 2. Check if the array needs resizing
        // 3. Add the item to the list. Increment noOfItems.
    }

    public void removeItem(String item) {
        // Check if the list contains this item; if so, remove it and call pack
        // NB! use equals to compare Strings, e.g. str1.equals(str2)
    }

    public String toString() {
        // Return a string of the form
        // [1st item; 2nd item; ...]
    }

    // Private (helper) methods
    private void pack(int index) {
        // In a loop, starting at "index", copy item at position+1 to position
        // (if the items are stored in "reverse order")
        // Decrement noOfItems.
    }

    private void resize() {
        // Create a new, temporary, reference and a corresponding String-array
        // Copy all item-references to the new array
        // Let the "theList" reference the new array (i.e. theItems = temp)
    }
}

有没有人有如何开始的指示?

1 个答案:

答案 0 :(得分:0)

通过为3种方法提供代码,让您领先一步。休息你可以自己尝试。

 // Public methods
  public int getNoOfItems() {
    return noOfItems;

  }

  public String getItemAt(int index) {
    if (index >= noOfItems) {
      return null;
    } else {
      return theItems[index];
    }
  }

  public String toString() {
    StringBuilder builder = new StringBuilder("[");
    for (int i = 0; i < theItems.length; i++) {
      if (theItems[i] != null) {
        builder.append(theItems[i]).append(";");
      }
      builder.append("]");
      return builder.toString();
    }