如何在java中将ArrayList转换为String ,Arraylist包含VO对象
请帮我转换ArrayList到String []。 ArrayList包含Object(VO)类型的值。
例如,
问题是我需要将国家/地区列表转换为字符串数组,对其进行排序,然后将其放入列表中。 但是我得到了ClassCastException。
String [] countriesArray = countryList.toArray(new String[countryList.size()]);
我假设您的国家/地区列表名称是countryList
。
因此,要将任何类的ArrayList转换为数组,请使用以下代码。 将T转换为要创建其数组的类。
List list = new ArrayList (); T [] countries = list.toArray(new T[list.size()]);
请帮我转换ArrayList为String [],ArrayList包含值对象(VO)作为值。
正如您所提到的那样,列表包含Values Object,即您自己的类,您需要重写String()以使其正常工作。
这段代码有效。 假设VO
是您的Value Object类。
List listOfValueObject = new ArrayList (); 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 sortedList = Arrays.asList(result);
的片段
List listOfValueObject = new ArrayList (); listOfValueObject.add(new VO()); String[] countriesArray = listOfValueObject.toArray(new String[listOfValueObject.size()]);
因为VO
不是随后从toArray
调用的本机方法arraycopy
所需的String
类型, ArrayStoreException
会给你ArrayStoreException
。
如果您的ArrayList
包含String
,您只需使用toArray
方法:
String[] array = list.toArray( new String[list.size()] );
如果情况并非如此(因为您的问题并不完全清楚),您将不得不手动循环遍历所有元素
List 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[]
数组是您将ArrayList
转换为的String
数组 - list是您手头的VO对象的
ArrayList
-
List#toArray(String[] object)
是将List对象转换为Array对象的方法
正如Viktor正确建议的那样,我编辑了我的代码片段。
这是ArrayList(toArray)中的一个方法,如:
List 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 countryList = Arrays.asList(countries);
在Java 8之前,我们可以选择迭代列表并填充数组,但是使用Java 8,我们也可以选择使用流。 检查以下代码:
//Populate few country objects where Country class stores name of country in field name. List 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);