我有一個方法,它接受一個陣列并將其以隨機順序復制到另一個陣列中并回傳打亂后的陣列。
但是,如果我想讓它通用,我無法創建 E 型別的第二個陣列。為了解決這個問題,我嘗試使用 Arraylist,然后使用 .toArray() 方法并將其轉換為 E 型別,但是回傳一個物件陣列。
我目前的解決方案是直接修改陣列并回傳它,但是有沒有辦法回傳正確型別的陣列,也就是傳遞給方法的陣列型別?
import java.util.ArrayList;
import java.util.Arrays;
public class ShuffleArray
{
public static void main(String[] args)
{
String[] list = {"bob", "maryo", "john", "david", "harry"};
//doesn't work, can't store array of objects in array of strings
list = shuffle(list);
//works because I modify directly
shuffle(list);
}
public static <E> E[] shuffle(E[] list)
{
ArrayList<E> shuffledList = new ArrayList<>();
//shuffle the array
while (shuffledList.size() != list.length)
{
int randomIndex = (int)(Math.random() * list.length);
if (!shuffledList.contains(list[randomIndex]))
{
shuffledList.add(list[randomIndex]);
}
}
//overwrites the initial values of the array with the shuffled ones
for (int i = 0; i < list.length; i )
{
list[i] = shuffledList.get(i);
}
//How do I make this return an array of type String?
return (E[]) shuffledList.toArray();
}
}
uj5u.com熱心網友回復:
所有陣列都有一個公共clone()方法,它回傳與原始陣列相同的型別:
return shuffledList.toArray(list.clone());
uj5u.com熱心網友回復:
你有一個不同的問題,在這里更好地描述:make arrayList.toArray() return more specific types
將您的退貨宣告更改為以下內容
return shuffledList.toArray(E[]::new);
uj5u.com熱心網友回復:
您可以使用Arrays.copyOf:
shuffledList.toArray(Arrays.copyOf(list, list.length));
盡管在內部該方法也使用強制轉換。
順便說一句,有一個內置方法Collections.shuffle。也許最好的方法是使用串列而不是原始陣列?
更新:要使 copyOf 方法起作用,您需要將型別引數系結到 Objects ,即將其從 更改<E>為<E extends Object>。該方法不適用于原始型別(int、long 等)。
uj5u.com熱心網友回復:
是的,你為什么不創建一個 E 型別的陣列并將值存盤在其中
E[] array = new E[list.length];
然后只需使用該陣列來存盤洗牌的值并回傳它
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426089.html
