![](/img/trans.png)
[英]JAVA: How to convert String ArrayList to Integer Arraylist?
[英]How to convert ArrayList to String[] in java, Arraylist contains VO objects
請幫我轉換ArrayList到String []。 ArrayList包含Object(VO)類型的值。
例如,
問題是我需要將國家/地區列表轉換為字符串數組,對其進行排序,然后將其放入列表中。 但是我得到了ClassCastException。
String [] countriesArray = countryList.toArray(new String[countryList.size()]);
我假設您的國家/地區列表名稱是countryList
。
因此,要將任何類的ArrayList轉換為數組,請使用以下代碼。 將T轉換為要創建其數組的類。
List<T> list = new ArrayList<T>();
T [] countries = list.toArray(new T[list.size()]);
請幫我轉換ArrayList到String [],ArrayList包含值對象(VO)作為值。
正如您所提到的那樣,list包含Values Object,即您自己的類,您需要重寫String()以使其正常工作。
這段代碼有效。 假設VO
是您的Value Object類。
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] result = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
result[i] = listOfValueObject.get(i).toString();
}
Arrays.sort(result);
List<String> sortedList = Arrays.asList(result);
的片段
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] countriesArray = listOfValueObject.toArray(new String[listOfValueObject.size()]);
將給你ArrayStoreException
因為VO
不是隨后從toArray
調用的本機方法arraycopy
所需的String
類型。
如果您的ArrayList
包含String
,您只需使用toArray
方法:
String[] array = list.toArray( new String[list.size()] );
如果不是這種情況(因為你的問題並不完全清楚),你必須手動循環遍歷所有元素
List<MyRandomObject> list;
String[] array = new String[list.size() ];
for( int i = 0; i < list.size(); i++ ){
MyRandomObject listElement = list.get(i);
array[i] = convertObjectToString( listElement );
}
String[] array = list.toArray(new String[list.size()]);
我們在這里做什么:
String[]
array是您需要將ArrayList
轉換為的String
數組 ArrayList
List#toArray(String[] object)
是將List對象轉換為Array對象的方法 正如Viktor正確建議的那樣,我編輯了我的代碼片段。
這是ArrayList(toArray)中的一個方法,如:
List<VO> listOfValueObject // is your value object
String[] countries = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
countries[i] = listOfValueObject.get(i).toString();
}
然后排序你有::
Arrays.sort(countries);
然后重新轉換為List ::
List<String> countryList = Arrays.asList(countries);
在Java 8之前,我們可以選擇迭代列表並填充數組,但是使用Java 8,我們也可以選擇使用流。 檢查以下代碼:
//Populate few country objects where Country class stores name of country in field name.
List<Country> countries = new ArrayList<>();
countries.add(new Country("India"));
countries.add(new Country("USA"));
countries.add(new Country("Japan"));
// Iterate over list
String[] countryArray = new String[countries.size()];
int index = 0;
for (Country country : countries) {
countryArray[index] = country.getName();
index++;
}
// Java 8 has option of streams to get same size array
String[] stringArrayUsingStream = countries.stream().map(c->c.getName()).toArray(String[]::new);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.