0
的數組在我的主類,我有:List<Person> allPeople = new ArrayList<>();
轉換對象的列表,以字符串
然後在課堂上我有一個返回所有的人Id
(人的String數組的方法具有的存取方法getId()
)。
什麼是最簡單的方式將列表轉換爲只有ID爲String的數組?
這是我目前的解決方案:
public String[] getAllId() {
Object[] allPeopleArray = allPeople.toArray();
String allId[] = new String[allPeople.size()];
for(int i=0; i<=allPeople.size()-1; i++){
allId[i] = ((Person)allPeopleArray [i]).getId();
}
return allId;
}
上述工作,但有一個「好」的方式來做到這一點?
你需要返回'String []'還是'List'可以接受嗎? –
[將集合轉換爲數組的最簡單方法]的可能重複(http://stackoverflow.com/questions/3293946/the-easiest-way-to-transform-collection-to-array) –
不是重複的,它是不只是轉換爲數組,它正在轉換爲一個特定屬性的數組(在這種情況下是 - id) – haimlit