为什么把数组转成列表再转成数组
Why convert an array to a list to an array again
我一直在使用 SpringBatch 并查看 class
的源代码
org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor<T>
我发现了这个:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = Arrays.asList(names).toArray(new String[names.length]);
}
- 数组转列表再转数组的目的是什么?
- 为什么不用这样的东西:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = names; // Simpler and without conversions
}
- 或者这样创建一个新的隔离实例:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = names.clone(); //Simpler and create a new instance
}
欢迎大家回答。
这通常是为了创建所提供数组的副本,尽管使用 System.arraycopy()
更容易做到。
需要复制的数组才能使接收对象不可变。考虑以下未完成复制的示例:
String[] names = { "John", "Pat", "Willy" };
obj.setNames(names);
names[0] = "Nathan";
// at which point obj.names also has Nathan
我一直在使用 SpringBatch 并查看 class
的源代码org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor<T>
我发现了这个:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = Arrays.asList(names).toArray(new String[names.length]);
}
- 数组转列表再转数组的目的是什么?
- 为什么不用这样的东西:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = names; // Simpler and without conversions
}
- 或者这样创建一个新的隔离实例:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = names.clone(); //Simpler and create a new instance
}
欢迎大家回答。
这通常是为了创建所提供数组的副本,尽管使用 System.arraycopy()
更容易做到。
需要复制的数组才能使接收对象不可变。考虑以下未完成复制的示例:
String[] names = { "John", "Pat", "Willy" };
obj.setNames(names);
names[0] = "Nathan";
// at which point obj.names also has Nathan