我有一个通用方法smallestValueInArray(T[] array)
,此方法获取任何类型的数组。此方法如下所示:
public class Helper {
public static <T extends Comparable<T>> T smallestValueInArray(T[] array) {
T smallestValue = array[0];
T smallerTempValue = array[0];
for (int i = 0; i < array.length - 2; i+=2) {
if (array[i].compareTo(array[i+1]) < 0) {
smallerTempValue = array[i];
} else {
smallerTempValue = array[i+1];
}
if (smallestValue.compareTo(smallerTempValue) > 0) {
smallestValue = smallerTempValue;
}
}
return smallestValue;
}
}
在Main方法中我想做这样的事情:
for (int i = 0; i < stringArray.length; i++) {
someOtherArray[i] = Helper.smallestValueInArray(stringArray);
Helper.deleteElement(stringArray, stringArray[i]);
}
所以我想遍历stringArray
,找到该数组中的最小元素,并将该元素添加到新数组someOtherArray
。之后我想使用方法deleteElement()
,这个方法得到两个参数,第一个是一个数组,第二个是该数组中应删除的元素位置。
我的deleteElement()
方法应该如何?
重要提示:我不想在List中转换我的数组,而是使用list.remove()!
答案 0 :(得分:5)
如果您不想将数组转换为List
,我看到的唯一选择是创建一个不包含已删除元素的新数组。您的deleteElement
方法必须返回该数组。
public static <T> T[] deleteElement(T[] array, int i)
{
// create new array of length array.length - 1
// copy all the elements from the source array except of the i'th element
// return the new array
}
并且您将其称为:
stringArray = Helper.deleteElement (stringArray, i);
当然,将数组转换为ArrayList
,删除i
&#39;元素并转换回数组会更简单。
答案 1 :(得分:0)
然后使用System.arraycopy
和有用的Arrays
类。
static <T> T[] deleteAt(T[] array, int i) {
int afteri = array.length - (i + 1);
if (afteri > 0) {
System.arraycopy(array, i + 1, array, i, afteri);
}
return array.copyOf(array, array.length - 1);
}
请注意,对于int,double和其他原始类型,需要重载函数。