[英]What is the most efficient way to add a string to this string array?
I have a string [] called myStrings. 我有一个名为myStrings的字符串[]。 I can't convert it to anything else, it has to stay a string array. 我不能将其转换为其他任何东西,它必须保留一个字符串数组。 However, I need to add one more string to it so I wrote this method. 但是,我需要再添加一个字符串,所以我编写了此方法。 I am sure there is a better, faster, less memory intensive way to do this but I can't see it. 我确信有更好,更快,更少内存占用的方法来执行此操作,但是我看不到它。 Can anyone provide a java api only way to solve this better than I have? 谁能提供Java api唯一比我更好的方法来解决此问题? I am using Java 1.7 我正在使用Java 1.7
String[] myStrings; // this gets set to real values later in program.
public void addToMyStrings(String addMe){
List<String> list = Arrays.asList( myStrings );
if( list != null )
{
list.add( addMe);
myStrings = list.toArray( new String[0] );
}
}
You can't add an item to a List<T>
returned by Arrays.asList(..)
: 您不能将项目添加到Arrays.asList(..)
返回的List<T>
:
Returns a fixed-size list backed by the specified array. 返回由指定数组支持的固定大小的列表。 (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). (更改为返回列表,将其“写入”到数组。)与Collection.toArray()结合使用,此方法充当基于数组的API和基于集合的API之间的桥梁。
You could use a separated List
that you build from the array manually or use directly just Arrays
: 您可以使用从阵列手动构建的单独List
,也可以直接使用Arrays
:
String[] newStrings = Arrays.copyOf(myStrings, myStrings.length()+1);
newStrings[myStrings.length()] = addMe;
If you absolutely have to use an Array then you could mimic what something like ArrayList does and double its size as needed. 如果您绝对必须使用Array,则可以模仿ArrayList之类的功能,并根据需要将其大小加倍。 That way most inserts are very efficient (O(1)) complexity, but every once in a while you will have to do a full arraycopy of O(n) complexity. 这样,大多数插入都是非常有效的(O(1))复杂度,但是偶尔您将不得不对O(n)复杂度进行完整的阵列复制。
This is bad design decision. 这是错误的设计决策。 If you need myStrings to change, then you need to declare it as a dynamic List from the beginning. 如果需要更改myStrings,则需要从头开始将其声明为动态列表。
If you want to keep it as a fixed-bound array, then try to give it a size that you know will never be exceeded upon instantiation. 如果要将其保留为固定绑定数组,请尝试为其指定一个您知道在实例化后不会超出的大小。
If you are unable to do that, you can use ArrayUtils.add(T[] array,T element) 如果无法执行此操作,则可以使用ArrayUtils.add(T [] array,T element)
The method copies your array and adds an item at the end. 该方法复制您的数组并在末尾添加一个项目。 It should be faster than your algorithm, but not by much. 它应该比您的算法快,但幅度不大。
For all practical purposes, I wouldn't worry about performance unless I see a bottleneck. 实际上,除非遇到瓶颈,否则我不会担心性能。 For example, if you expect your array to contain 3-4 items, there is not point in worrying about this for the moment. 例如,如果您希望数组包含3-4个项目,那么暂时不必担心这一点。 Premature optimization is evil. 过早的优化是邪恶的。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.