Skip to content

Commit

Permalink
Call 'toArray()' with an empty array instead of a pre-sized array
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
adnapibar committed Nov 16, 2022
1 parent aea7d09 commit 2154282
Show file tree
Hide file tree
Showing 145 changed files with 212 additions and 265 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- Relax visibility of the HTTP_CHANNEL_KEY and HTTP_SERVER_CHANNEL_KEY to make it possible for the plugins to access associated Netty4HttpChannel / Netty4HttpServerChannel instance ([#4638](https://github.com/opensearch-project/OpenSearch/pull/4638))
- Use ReplicationFailedException instead of OpensearchException in ReplicationTarget ([#4725](https://github.com/opensearch-project/OpenSearch/pull/4725))
- Migrate client transports to Apache HttpClient / Core 5.x ([#4459](https://github.com/opensearch-project/OpenSearch/pull/4459))
- Call 'toArray()' with an empty array instead of a pre-sized array ([#5277](https://github.com/opensearch-project/OpenSearch/pull/5277))

### Deprecated

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,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 @@ -435,7 +435,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 @@ -1028,7 +1028,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 @@ -68,12 +68,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 @@ -101,7 +101,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, final String segment) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,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 @@ -310,7 +310,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 @@ -517,7 +517,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 @@ -708,7 +708,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 @@ -163,7 +163,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 @@ -194,7 +194,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 @@ -589,7 +589,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 @@ -147,7 +147,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 @@ -176,7 +176,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 @@ -162,7 +162,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 @@ -214,7 +214,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 @@ -254,7 +254,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 @@ -313,7 +313,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 @@ -362,7 +362,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 @@ -419,7 +419,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 @@ -500,7 +500,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 @@ -514,7 +514,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 @@ -148,7 +148,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 @@ -200,7 +200,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 @@ -240,7 +240,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 @@ -299,7 +299,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 @@ -357,7 +357,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 @@ -438,7 +438,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 @@ -452,6 +452,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 @@ -85,7 +85,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 2154282

Please sign in to comment.