Skip to content

Commit

Permalink
Call 'toArray()' with an empty array instead of a pre-sized array (#5277
Browse files Browse the repository at this point in the history
) (#16563)

Calls to `Collection.toArray()` is not consistent and in many places and use a
pre-sized array parameter. This change makes a consistent use of the
`toArray(new T[0])`. The empty array usage is considered faster, safer and
cleaner than the sized based array approach.

Signed-off-by: Rabi Panda <[email protected]>
Co-authored-by: Rabi Panda <[email protected]>
  • Loading branch information
andrross and adnapibar authored Nov 5, 2024
1 parent 2fa8370 commit 6557176
Show file tree
Hide file tree
Showing 142 changed files with 206 additions and 254 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ private static void addIvyRepo(Project project, String name, String url, String

project.getRepositories().exclusiveContent(exclusiveContentRepository -> {
exclusiveContentRepository.filter(config -> config.includeGroup(group));
exclusiveContentRepository.forRepositories(repos.toArray(new IvyArtifactRepository[repos.size()]));
exclusiveContentRepository.forRepositories(repos.toArray(new IvyArtifactRepository[0]));
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ static ShardStats fromXContent(XContentParser parser) throws IOException {
parser.skipChildren();
}
}
return new ShardStats(successfulShards, totalShards, skippedShards, failures.toArray(new ShardSearchFailure[failures.size()]));
return new ShardStats(successfulShards, totalShards, skippedShards, failures.toArray(new ShardSearchFailure[0]));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ public PutIndexTemplateRequest alias(Alias alias) {

@Override
public String[] indices() {
return indexPatterns.toArray(new String[indexPatterns.size()]);
return indexPatterns.toArray(new String[0]);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ static CustomResponseSection2 fromXContent(XContentParser parser) throws IOExcep
values.add(parser.text());
}
assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken());
CustomResponseSection2 responseSection2 = new CustomResponseSection2(values.toArray(new String[values.size()]));
CustomResponseSection2 responseSection2 = new CustomResponseSection2(values.toArray(new String[0]));
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
return responseSection2;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1027,7 +1027,7 @@ private static void setFileAttributes(final Path path, final Set<PosixFilePermis

@Override
public void close() throws IOException {
IOUtils.rm(pathsToDeleteOnShutdown.toArray(new Path[pathsToDeleteOnShutdown.size()]));
IOUtils.rm(pathsToDeleteOnShutdown.toArray(new Path[0]));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ void execute(Terminal terminal, Environment env, String pluginName, boolean purg
// finally, add the marker file
pluginPaths.add(removing);

IOUtils.rm(pluginPaths.toArray(new Path[pluginPaths.size()]));
IOUtils.rm(pluginPaths.toArray(new Path[0]));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public void testRandomIterators() {
}
iterators[i] = theseValues.iterator();
}
assertContainsInOrder(Iterators.concat(iterators), values.toArray(new Integer[values.size()]));
assertContainsInOrder(Iterators.concat(iterators), values.toArray(new Integer[0]));
}

public void testTwoEntries() {
Expand Down
4 changes: 2 additions & 2 deletions libs/core/src/main/java/org/opensearch/core/ParseField.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,12 @@ public ParseField(String name, String... deprecatedNames) {
} else {
final HashSet<String> set = new HashSet<>();
Collections.addAll(set, deprecatedNames);
this.deprecatedNames = set.toArray(new String[set.size()]);
this.deprecatedNames = set.toArray(new String[0]);
}
Set<String> allNames = new HashSet<>();
allNames.add(name);
Collections.addAll(allNames, this.deprecatedNames);
this.allNames = allNames.toArray(new String[allNames.size()]);
this.allNames = allNames.toArray(new String[0]);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ public static String[] toStringArray(final Collection<String> collection) {
if (collection == null) {
return null;
}
return collection.toArray(new String[collection.size()]);
return collection.toArray(new String[0]);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ static ByteBuffer[] toByteBuffers(BytesReference reference) {
while ((r = byteRefIterator.next()) != null) {
buffers.add(ByteBuffer.wrap(r.bytes, r.offset, r.length));
}
return buffers.toArray(new ByteBuffer[buffers.size()]);
return buffers.toArray(new ByteBuffer[0]);

} catch (IOException e) {
// this is really an error since we don't do IO in our bytesreferences
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public static FilterPath[] compile(Set<String> filters) {
}
}
}
return paths.toArray(new FilterPath[paths.size()]);
return paths.toArray(new FilterPath[0]);
}

private static FilterPath parse(final String filter) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private TokenFilter evaluate(String name, FilterPath[] filters) {
}

if ((nextFilters != null) && (nextFilters.isEmpty() == false)) {
return new FilterPathBasedFilter(nextFilters.toArray(new FilterPath[nextFilters.size()]), inclusive);
return new FilterPathBasedFilter(nextFilters.toArray(new FilterPath[0]), inclusive);
}
}
return NO_MATCHING;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ public void testHasParentFilter() throws Exception {
}
assertThat(parentToChildren.get(previousParentId).add(childId), is(true));
}
indexRandom(true, builders.toArray(new IndexRequestBuilder[builders.size()]));
indexRandom(true, builders.toArray(new IndexRequestBuilder[0]));

assertThat(parentToChildren.isEmpty(), equalTo(false));
for (Map.Entry<String, Set<String>> parentToChildrenEntry : parentToChildren.entrySet()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ protected void doExecute(Task task, RankEvalRequest request, ActionListener<Rank
if (summaryFields.isEmpty()) {
evaluationRequest.fetchSource(false);
} else {
evaluationRequest.fetchSource(summaryFields.toArray(new String[summaryFields.size()]), new String[0]);
evaluationRequest.fetchSource(summaryFields.toArray(new String[0]), new String[0]);
}
SearchRequest searchRequest = new SearchRequest(request.indices(), evaluationRequest);
searchRequest.indicesOptions(request.indicesOptions());
Expand All @@ -158,12 +158,7 @@ protected void doExecute(Task task, RankEvalRequest request, ActionListener<Rank
assert ratedRequestsInSearch.size() == msearchRequest.requests().size();
client.multiSearch(
msearchRequest,
new RankEvalActionListener(
listener,
metric,
ratedRequestsInSearch.toArray(new RatedRequest[ratedRequestsInSearch.size()]),
errors
)
new RankEvalActionListener(listener, metric, ratedRequestsInSearch.toArray(new RatedRequest[0]), errors)
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ void refreshAndFinish(List<Failure> indexingFailures, List<SearchFailure> search
return;
}
RefreshRequest refresh = new RefreshRequest();
refresh.indices(destinationIndices.toArray(new String[destinationIndices.size()]));
refresh.indices(destinationIndices.toArray(new String[0]));
logger.debug("[{}]: refreshing", task.getId());
client.admin().indices().refresh(refresh, new ActionListener<RefreshResponse>() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ public void testMultipleSources() throws Exception {
int slices = randomSlices(1, 10);
int expectedSlices = expectedSliceStatuses(slices, docs.keySet());

String[] sourceIndexNames = docs.keySet().toArray(new String[docs.size()]);
String[] sourceIndexNames = docs.keySet().toArray(new String[0]);

assertThat(
deleteByQuery().source(sourceIndexNames).filter(QueryBuilders.matchAllQuery()).refresh(true).setSlices(slices).get(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public void testMultipleSources() throws Exception {
int slices = randomSlices(1, 10);
int expectedSlices = expectedSliceStatuses(slices, docs.keySet());

String[] sourceIndexNames = docs.keySet().toArray(new String[docs.size()]);
String[] sourceIndexNames = docs.keySet().toArray(new String[0]);
ReindexRequestBuilder request = reindex().source(sourceIndexNames).destination("dest").refresh(true).setSlices(slices);

BulkByScrollResponse response = request.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public void testMultipleSources() throws Exception {
int slices = randomSlices(1, 10);
int expectedSlices = expectedSliceStatuses(slices, docs.keySet());

String[] sourceIndexNames = docs.keySet().toArray(new String[docs.size()]);
String[] sourceIndexNames = docs.keySet().toArray(new String[0]);
BulkByScrollResponse response = updateByQuery().source(sourceIndexNames).refresh(true).setSlices(slices).get();
assertThat(response, matcher().updated(allDocs.size()).slices(hasSize(expectedSlices)));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public AnnotationToken[] getIntersectingAnnotations(int start, int end) {
// add 1 for the fieldvalue separator character
fieldValueOffset += fieldValueAnnotations.textMinusMarkup.length() + 1;
}
return intersectingAnnotations.toArray(new AnnotationToken[intersectingAnnotations.size()]);
return intersectingAnnotations.toArray(new AnnotationToken[0]);
}

private void append(StringBuilder dest, String content, int start, int end) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,7 @@ private String[] randomUniqueIndices() {
while (uniqueIndices.size() < count) {
uniqueIndices.add(randomFrom(this.indices));
}
return uniqueIndices.toArray(new String[uniqueIndices.size()]);
return uniqueIndices.toArray(new String[0]);
}

private static void assertAllRequestsHaveBeenConsumed() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public void testSimpleMixedFeatures() {
}
GetIndexResponse response = runWithRandomFeatureMethod(
client().admin().indices().prepareGetIndex().addIndices("idx"),
features.toArray(new Feature[features.size()])
features.toArray(new Feature[0])
);
String[] indices = response.indices();
assertThat(indices, notNullValue());
Expand Down Expand Up @@ -193,7 +193,7 @@ public void testEmptyMixedFeatures() {
}
GetIndexResponse response = runWithRandomFeatureMethod(
client().admin().indices().prepareGetIndex().addIndices("empty_idx"),
features.toArray(new Feature[features.size()])
features.toArray(new Feature[0])
);
String[] indices = response.indices();
assertThat(indices, notNullValue());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@ public void testIndexSearchAndRelocateConcurrently() throws Exception {
logger.info(" --> checking iteration {}", i);
SearchResponse afterRelocation = client().prepareSearch().setSize(ids.size()).get();
assertNoFailures(afterRelocation);
assertSearchHits(afterRelocation, ids.toArray(new String[ids.size()]));
assertSearchHits(afterRelocation, ids.toArray(new String[0]));
}
stopped.set(true);
for (Thread searchThread : searchThreads) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public void setupSuiteScopeCluster() throws Exception {
.setSource(jsonBuilder().startObject().field("value", i * 2).field("location", "52.0945, 5.116").endObject())
);
}
indexRandom(true, builders.toArray(new IndexRequestBuilder[builders.size()]));
indexRandom(true, builders.toArray(new IndexRequestBuilder[0]));
ensureSearchable();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public void setupSuiteScopeCluster() throws Exception {

getMultiSortDocs(builders);

indexRandom(true, builders.toArray(new IndexRequestBuilder[builders.size()]));
indexRandom(true, builders.toArray(new IndexRequestBuilder[0]));
ensureSearchable();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public void testDocCountTopLevel() throws Exception {
assertThat(maxBucketValue, notNullValue());
assertThat(maxBucketValue.getName(), equalTo("max_bucket"));
assertThat(maxBucketValue.value(), equalTo(maxValue));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()])));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0])));
}

public void testDocCountAsSubAgg() throws Exception {
Expand Down Expand Up @@ -240,7 +240,7 @@ public void testDocCountAsSubAgg() throws Exception {
assertThat(maxBucketValue, notNullValue());
assertThat(maxBucketValue.getName(), equalTo("max_bucket"));
assertThat(maxBucketValue.value(), equalTo(maxValue));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()])));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0])));
}
}

Expand Down Expand Up @@ -280,7 +280,7 @@ public void testMetricTopLevel() throws Exception {
assertThat(maxBucketValue, notNullValue());
assertThat(maxBucketValue.getName(), equalTo("max_bucket"));
assertThat(maxBucketValue.value(), equalTo(maxValue));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()])));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0])));
}

public void testMetricAsSubAgg() throws Exception {
Expand Down Expand Up @@ -339,7 +339,7 @@ public void testMetricAsSubAgg() throws Exception {
assertThat(maxBucketValue, notNullValue());
assertThat(maxBucketValue.getName(), equalTo("max_bucket"));
assertThat(maxBucketValue.value(), equalTo(maxValue));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()])));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0])));
}
}

Expand Down Expand Up @@ -388,7 +388,7 @@ public void testMetricAsSubAggOfSingleBucketAgg() throws Exception {
assertThat(maxBucketValue, notNullValue());
assertThat(maxBucketValue.getName(), equalTo("max_bucket"));
assertThat(maxBucketValue.value(), equalTo(maxValue));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()])));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0])));
}

public void testMetricAsSubAggWithInsertZeros() throws Exception {
Expand Down Expand Up @@ -445,7 +445,7 @@ public void testMetricAsSubAggWithInsertZeros() throws Exception {
assertThat(maxBucketValue, notNullValue());
assertThat(maxBucketValue.getName(), equalTo("max_bucket"));
assertThat(maxBucketValue.value(), equalTo(maxValue));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()])));
assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0])));
}
}

Expand Down Expand Up @@ -526,7 +526,7 @@ public void testNested() throws Exception {
assertThat(maxBucketValue, notNullValue());
assertThat(maxBucketValue.getName(), equalTo("max_histo_bucket"));
assertThat(maxBucketValue.value(), equalTo(maxHistoValue));
assertThat(maxBucketValue.keys(), equalTo(maxHistoKeys.toArray(new String[maxHistoKeys.size()])));
assertThat(maxBucketValue.keys(), equalTo(maxHistoKeys.toArray(new String[0])));
if (maxHistoValue > maxTermsValue) {
maxTermsValue = maxHistoValue;
maxTermsKeys = new ArrayList<>();
Expand All @@ -540,7 +540,7 @@ public void testNested() throws Exception {
assertThat(maxBucketValue, notNullValue());
assertThat(maxBucketValue.getName(), equalTo("max_terms_bucket"));
assertThat(maxBucketValue.value(), equalTo(maxTermsValue));
assertThat(maxBucketValue.keys(), equalTo(maxTermsKeys.toArray(new String[maxTermsKeys.size()])));
assertThat(maxBucketValue.keys(), equalTo(maxTermsKeys.toArray(new String[0])));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public void testDocCountTopLevel() throws Exception {
assertThat(minBucketValue, notNullValue());
assertThat(minBucketValue.getName(), equalTo("min_bucket"));
assertThat(minBucketValue.value(), equalTo(minValue));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()])));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0])));
}

public void testDocCountAsSubAgg() throws Exception {
Expand Down Expand Up @@ -226,7 +226,7 @@ public void testDocCountAsSubAgg() throws Exception {
assertThat(minBucketValue, notNullValue());
assertThat(minBucketValue.getName(), equalTo("min_bucket"));
assertThat(minBucketValue.value(), equalTo(minValue));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()])));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0])));
}
}

Expand Down Expand Up @@ -266,7 +266,7 @@ public void testMetricTopLevel() throws Exception {
assertThat(minBucketValue, notNullValue());
assertThat(minBucketValue.getName(), equalTo("min_bucket"));
assertThat(minBucketValue.value(), equalTo(minValue));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()])));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0])));
}

public void testMetricAsSubAgg() throws Exception {
Expand Down Expand Up @@ -325,7 +325,7 @@ public void testMetricAsSubAgg() throws Exception {
assertThat(minBucketValue, notNullValue());
assertThat(minBucketValue.getName(), equalTo("min_bucket"));
assertThat(minBucketValue.value(), equalTo(minValue));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()])));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0])));
}
}

Expand Down Expand Up @@ -383,7 +383,7 @@ public void testMetricAsSubAggWithInsertZeros() throws Exception {
assertThat(minBucketValue, notNullValue());
assertThat(minBucketValue.getName(), equalTo("min_bucket"));
assertThat(minBucketValue.value(), equalTo(minValue));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()])));
assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0])));
}
}

Expand Down Expand Up @@ -464,7 +464,7 @@ public void testNested() throws Exception {
assertThat(minBucketValue, notNullValue());
assertThat(minBucketValue.getName(), equalTo("min_histo_bucket"));
assertThat(minBucketValue.value(), equalTo(minHistoValue));
assertThat(minBucketValue.keys(), equalTo(minHistoKeys.toArray(new String[minHistoKeys.size()])));
assertThat(minBucketValue.keys(), equalTo(minHistoKeys.toArray(new String[0])));
if (minHistoValue < minTermsValue) {
minTermsValue = minHistoValue;
minTermsKeys = new ArrayList<>();
Expand All @@ -478,6 +478,6 @@ public void testNested() throws Exception {
assertThat(minBucketValue, notNullValue());
assertThat(minBucketValue.getName(), equalTo("min_terms_bucket"));
assertThat(minBucketValue.value(), equalTo(minTermsValue));
assertThat(minBucketValue.keys(), equalTo(minTermsKeys.toArray(new String[minTermsKeys.size()])));
assertThat(minBucketValue.keys(), equalTo(minTermsKeys.toArray(new String[0])));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ private void testSearchAndRelocateConcurrently(final int numberOfReplicas) throw
)
);
}
indexRandom(true, indexBuilders.toArray(new IndexRequestBuilder[indexBuilders.size()]));
indexRandom(true, indexBuilders.toArray(new IndexRequestBuilder[0]));
assertHitCount(client().prepareSearch().get(), (numDocs));
final int numIters = scaledRandomIntBetween(5, 20);
for (int i = 0; i < numIters; i++) {
Expand Down
Loading

0 comments on commit 6557176

Please sign in to comment.