Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
移除&;替换java的方法_Java_Arrays_List_Interface_Bag - Fatal编程技术网

移除&;替换java的方法

移除&;替换java的方法,java,arrays,list,interface,bag,Java,Arrays,List,Interface,Bag,因此,我很难对以下问题的答案进行概念化。我不是在寻找答案,而是我可以采取哪些有用的步骤,使我能够自己提出答案。注:为了回答这些问题,我得到了参考类和驱动程序。问题如下: Q.1为ADT包实施一种替换方法,该方法使用 给定对象 Q.2.编写一个remove方法来删除ArrayBag中元素的每个实例 问题3。至少给出两个固定行李适用的示例和两个可调整大小的行李适用的示例 以下代码是我开始编写的代码,但不确定方向是否正确: a.1 public T replace(T theItem) { R

因此,我很难对以下问题的答案进行概念化。我不是在寻找答案,而是我可以采取哪些有用的步骤,使我能够自己提出答案。注:为了回答这些问题,我得到了参考类和驱动程序。问题如下:

Q.1为ADT包实施一种替换方法,该方法使用 给定对象

Q.2.编写一个remove方法来删除ArrayBag中元素的每个实例

问题3。至少给出两个固定行李适用的示例和两个可调整大小的行李适用的示例

以下代码是我开始编写的代码,但不确定方向是否正确:

a.1 public T replace(T theItem) {
    Random generator = new Random();
    int randomPosition = generator.nextInt(numberOfEntries);

    T result = null;

    if (!isEmpty() && (randomPosition >= 0)) {
        result = bag[randomPosition]; // Entry to remove
        bag[randomPosition] = theItem; // Replace entry to remove with
                                // last entry

    }
    return result;
 a.2 public void clear(T theItem) {
    while (!this.isEmpty(ArrayBag))
        this.remove();

 a.3 not sure it should be related to coding examples or something else.
此外,ArrayBag的类别如下所示,以供参考:

import java.util.Arrays;
import java.util.Random;

public final class ArrayBag<T> implements  BagInterface<T> {
private final T[] bag;
private int numberOfEntries;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;

/** Creates an empty bag whose initial capacity is 25. */
public ArrayBag() {
    this(DEFAULT_CAPACITY);
} // end default constructor

/**
 * Creates an empty bag having a given capacity.
 * 
 * @param desiredCapacity
 *            The integer capacity desired.
 */
public ArrayBag(int desiredCapacity) {
    if (desiredCapacity <= MAX_CAPACITY) {
        // The cast is safe because the new array contains null entries
        @SuppressWarnings("unchecked")
        T[] tempBag = (T[]) new Object[desiredCapacity]; // Unchecked cast
        bag = tempBag;
        numberOfEntries = 0;
        initialized = true;
    } else
        throw new IllegalStateException("Attempt to create a bag "
                + "whose capacity exceeds " + "allowed maximum.");
  } // end constructor

  /**
   * Adds a new entry to this bag.
   * 
   * @param newEntry
  *            The object to be added as a new entry.
  * @return True if the addition is successful, or false if not.
 * /
  public boolean add(T newEntry) {
    checkInitialization();
    boolean result = true;
    if (isArrayFull()) {
        result = false;
    } else { // Assertion: result is true here
        bag[numberOfEntries] = newEntry;
        numberOfEntries++;
    } // end if

    return result;
  } // end add

 /**
 * Retrieves all entries that are in this bag.
 * 
 * @return A newly allocated array of all the entries in this bag.
 */
public T[] toArray() {
    checkInitialization();

    // The cast is safe because the new array contains null entries.
    @SuppressWarnings("unchecked")
    T[] result = (T[]) new Object[numberOfEntries]; // Unchecked cast

    for (int index = 0; index < numberOfEntries; index++) {
        result[index] = bag[index];
    } // end for

    return result;
    // Note: The body of this method could consist of one return statement,
    // if you call Arrays.copyOf
} // end toArray

/**
 * Sees whether this bag is empty.
 * 
 * @return True if this bag is empty, or false if not.
 */
public boolean isEmpty() {
    return numberOfEntries == 0;
} // end isEmpty

/**
 * Gets the current number of entries in this bag.
 * 
 * @return The integer number of entries currently in this bag.
 */
public int getCurrentSize() {
    return numberOfEntries;
} // end getCurrentSize

/**
 * Counts the number of times a given entry appears in this bag.
 * 
 * @param anEntry
 *            The entry to be counted.
 * @return The number of times anEntry appears in this ba.
 */
public int getFrequencyOf(T anEntry) {
    checkInitialization();
    int counter = 0;

    for (int index = 0; index < numberOfEntries; index++) {
        if (anEntry.equals(bag[index])) {
            counter++;
        } // end if
    } // end for

    return counter;
} // end getFrequencyOf

/**
 * Tests whether this bag contains a given entry.
 * 
 * @param anEntry
 *            The entry to locate.
 * @return True if this bag contains anEntry, or false otherwise.
 */
public boolean contains(T anEntry) {
    checkInitialization();
    return getIndexOf(anEntry) > -1; // or >= 0
} // end contains

/** Removes all entries from this bag. */
public void clear() {
    while (!this.isEmpty())
        this.remove();
} // end clear

/**
 * Removes one unspecified entry from this bag, if possible.
 * 
 * @return Either the removed entry, if the removal was successful, or null.
 */
public T remove() {
    checkInitialization();
    T result = removeEntry(numberOfEntries - 1);
    return result;
} // end remove

/**
 * Removes one occurrence of a given entry from this bag.
 * 
 * @param anEntry
 *            The entry to be removed.
 * @return True if the removal was successful, or false if not.
 */
public boolean remove(T anEntry) {
    checkInitialization();
    int index = getIndexOf(anEntry);
    T result = removeEntry(index);
    return anEntry.equals(result);
} // end remove

public boolean removeRandom() {
    Random generator = new Random();
    int randomPosition = generator.nextInt(numberOfEntries);
    T result = removeEntry(randomPosition);
    if (result == null) {
        return false;
    } else {
        return true;
    }

}

@Override
public boolean equals(Object obj) {
    if (obj instanceof ArrayBag) {
        ArrayBag<T> otherArrayBag = (ArrayBag<T>) obj;

        if (numberOfEntries == otherArrayBag.numberOfEntries) {

            // I create new arrays so that I can manipulate them
            // and it will not alter this.bag or otherArrayBag.bag
            T[] currentBagTempArray = toArray();
            T[] otherBagTempArray = otherArrayBag.toArray();

            Arrays.sort(currentBagTempArray);
            Arrays.sort(otherBagTempArray);

            for (int i = 0; i < numberOfEntries; i++) {
                if (!currentBagTempArray[i].equals(otherBagTempArray[i])) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }

    } else {
        return false;
    }
}

public ResizableArrayBag<T> createResizableArray() {
    T[] currentBagContents = toArray();
    ResizableArrayBag<T> newBag = new ResizableArrayBag<T>(currentBagContents);
    return newBag;
}

// Returns true if the array bag is full, or false if not.
private boolean isArrayFull() {
    return numberOfEntries >= bag.length;
} // end isArrayFull

// Locates a given entry within the array bag.
// Returns the index of the entry, if located,
// or -1 otherwise.
// Precondition: checkInitialization has been called.
private int getIndexOf(T anEntry) {
    int where = -1;
    boolean found = false;
    int index = 0;

    while (!found && (index < numberOfEntries)) {
        if (anEntry.equals(bag[index])) {
            found = true;
            where = index;
        } // end if
        index++;
    } // end while

    // Assertion: If where > -1, anEntry is in the array bag, and it
    // equals bag[where]; otherwise, anEntry is not in the array.

    return where;
} // end getIndexOf

// Removes and returns the entry at a given index within the array.
// If no such entry exists, returns null.
// Precondition: 0 <= givenIndex < numberOfEntries.
// Precondition: checkInitialization has been called.
private T removeEntry(int givenIndex) {
    T result = null;

    if (!isEmpty() && (givenIndex >= 0)) {
        result = bag[givenIndex]; // Entry to remove
        int lastIndex = numberOfEntries - 1;
        bag[givenIndex] = bag[lastIndex]; // Replace entry to remove with
                                            // last entry
        bag[lastIndex] = null; // Remove reference to last entry
        numberOfEntries--;
    } // end if

    return result;
} // end removeEntry

// Throws an exception if this object is not initialized.
private void checkInitialization() {
    if (!initialized)
        throw new SecurityException(
                "ArrayBag object is not initialized properly.");
} // end checkInitialization
导入java.util.array;
导入java.util.Random;
公共最终类ArrayBag实现了BagInterface{
私人最终T[]包;
私人int numberOfEntries;
私有布尔初始化=false;
专用静态最终int默认_容量=25;
专用静态最终int最大容量=10000;
/**创建初始容量为25的空包*/
公共ArrayBag(){
这(默认容量);
}//结束默认构造函数
/**
*创建具有给定容量的空包。
* 
*@param desiredCapacity
*所需的整数容量。
*/
公共阵列袋(内部期望容量){
如果(所需容量-1;//或>=0
}//结束包含
/**删除此包中的所有条目*/
公共空间清除(){
而(!this.isEmpty())
这个。删除();
}//结束清除
/**
*如果可能,从该行李中删除一个未指定的条目。
* 
*@如果删除成功,则返回删除的条目,或返回null。
*/
公共部门不能删除(){
检查初始化();
T结果=removeEntry(numberOfEntries-1);
返回结果;
}//结束删除
/**
*从此包中删除给定条目的一次出现。
* 
*@param-anEntry
*要删除的条目。
*@如果删除成功,则返回True;否则返回false。
*/
公共布尔删除(T anEntry){
检查初始化();
int index=getIndexOf(anEntry);
T结果=移除中心(索引);
返回一个entry.equals(结果);
}//结束删除
公共布尔值删除程序ANDOM(){
随机生成器=新随机();
int randomPosition=generator.nextInt(numberOfEntries);
T结果=移动中心(随机位置);
如果(结果==null){
返回false;
}否则{
返回true;
}
}
@凌驾
公共布尔等于(对象obj){
if(ArrayBag的obj实例){
ArrayBag otherArrayBag=(ArrayBag)obj;
if(numberOfEntries==otherArrayBag.numberOfEntries){
//我创建了新的数组,以便可以对它们进行操作
//它不会改变这个.bag或其他ArrayBag.bag
T[]currentBagTempArray=toArray();
T[]otherBagTempArray=otherArrayBag.toArray();
Arrays.sort(currentBagTempArray);
Arrays.sort(otherBagTempArray);
for(int i=0;i=行李长度;
}//结束isArrayFull
//在数组包中查找给定条目。
//返回条目的索引(如果找到),
//否则为-1。
//前提条件:已调用checkInitialization。
private int getIndexOf(T anEntry){
int其中=-1;
布尔值=false;
int指数=0;
而(!found&(索引-1,则数组包中有一个入口,并且
//等于bag[where];否则,数组中不存在entry。
返回哪里;
}//结束getIndexOf
//移除并返回数组中给定索引处的项。
//如果不存在这样的条目,则返回null。
//前提条件:0=0){
结果=行李[GivinIndex];//要删除的条目
int lastIndex=numberOfEntries-1;
bag[GivinIndex]=bag[lastIndex];//替换要删除的条目
//最后一项
bag[lastIndex]=null;//删除对最后一个条目的引用
条目数--;
}//如果结束,则结束
返回结果;
}//结束removeEntry
//如果此对象未初始化,则引发异常。
私有void检查初始化(){
如果(!已初始化)
抛出新的SecurityException(
“ArrayBag对象未正确初始化。”);
}//结束检查初始化

}//end ArrayBag

我查看了您的起始代码和类,但没有运行它。 但我可以说你们的方向是正确的

对于Q2,您应该在数组中搜索给定的元素并删除每个元素。因为问题明确地说“删除元素的每个实例”,所以请检查getIndexOf()方法。您可以看到如何搜索和删除元素。如果找到一个匹配的,请将其删除。在对元素进行迭代时,如果删除和元素,请小心。如果在迭代时删除一个元素,则大小将更改。我建议您将每个匹配项存储在一个数组中。迭代后,对每个找到的元素使用remove(index)方法

Give at least two examples of a situation where a fixed bag is appropriate and two examples of a situation where a resizable bag is appropriate.
对于这个项目,您可以添加一些解释和一些示例代码或算法。 我可以给你两件事:

1.  If the array is not getting full too fast fixed size is good. But if array is getting full too fast you should resize new array and copy all elements again and again. Overhead amount is important.
2. Amount of capacity is important. How you will decide initial size ? Big size or small size ? Think that
我希望
public boolean replace(T findMe, T replacement)