一、List 转 String[]
@Test
void arraysTostr() {
List<String> list = new ArrayList<>();
list.add("mm");
list.add("nn");
list.add("hh");
String[] strings = list.toArray(new String[list.size()]);
System.out.println(strings.length);
}
输出: 3
二、 String[] 转List
@Test
void strToArrays() {
String[] strs = new String[]{"mm","nn","hh"};
List<String> list = Arrays.asList(strs);
System.out.println(list.toString());
}
输出: [mm, nn, hh]
三、Error:java.lang.UnsupportedOperationException
@Test
void strToArrays() {
String[] strs = new String[]{"mm","nn","hh"};
List<String> list = Arrays.asList(strs);
list.add("vv");
System.out.println(list.toString());
}
执行了上边的测试数据后会发现将String[]转化为List之后,再执行list.add操作会抛出以下异常
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.yd.redisassistant.RedisAssistantApplicationTests.strToArrays(RedisAssistantApplicationTests.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:532)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:108)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
at java.util.ArrayList.forEach(ArrayList.java:1249)
原因如下:
AbstractList中add方法是默认throw UnsupportedOperationException而且不作任何操作。
Arrays的内部类ArrayList没有重新实现,所以会抛出异常
java.util.ArrayList重写了方法
解决方法如下:
@Test
void strToArrays() {
String[] strs = new String[]{"mm","nn","hh"};
List<String> list = new ArrayList<>(Arrays.asList(strs));
list.add("vv");
System.out.println(list.toString());
}
输出: [mm, nn, hh, vv]
下边是Arrays.asList的内部类: