Skip to content

Commit

Permalink
8284780: Need methods to create pre-sized HashSet and LinkedHashSet
Browse files Browse the repository at this point in the history
Reviewed-by: naoto, bpb, dfuchs, ascarpino
  • Loading branch information
XenoAmess authored and Stuart Marks committed Jun 9, 2022
1 parent a941bc2 commit e01cd7c
Show file tree
Hide file tree
Showing 29 changed files with 147 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private PBEKeyFactory(String keytype) {
}

static {
validTypes = new HashSet<>(17);
validTypes = HashSet.newHashSet(17);
validTypes.add("PBEWithMD5AndDES".toUpperCase(Locale.ENGLISH));
validTypes.add("PBEWithSHA1AndDESede".toUpperCase(Locale.ENGLISH));
validTypes.add("PBEWithSHA1AndRC2_40".toUpperCase(Locale.ENGLISH));
Expand Down
2 changes: 1 addition & 1 deletion src/java.base/share/classes/java/io/ObjectStreamClass.java
Original file line number Diff line number Diff line change
Expand Up @@ -1648,7 +1648,7 @@ private static ObjectStreamField[] getDeclaredSerialFields(Class<?> cl)

ObjectStreamField[] boundFields =
new ObjectStreamField[serialPersistentFields.length];
Set<String> fieldNames = new HashSet<>(serialPersistentFields.length);
Set<String> fieldNames = HashSet.newHashSet(serialPersistentFields.length);

for (int i = 0; i < serialPersistentFields.length; i++) {
ObjectStreamField spf = serialPersistentFields[i];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ private Class<?> generateInnerClass() throws LambdaConversionException {
interfaceNames = new String[]{interfaceName};
} else {
// Assure no duplicate interfaces (ClassFormatError)
Set<String> itfs = new LinkedHashSet<>(altInterfaces.length + 1);
Set<String> itfs = LinkedHashSet.newLinkedHashSet(altInterfaces.length + 1);
itfs.add(interfaceName);
for (Class<?> i : altInterfaces) {
itfs.add(i.getName().replace('.', '/'));
Expand Down
2 changes: 1 addition & 1 deletion src/java.base/share/classes/java/nio/charset/Charset.java
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ public final Set<String> aliases() {
if (aliasSet != null)
return aliasSet;
int n = aliases.length;
HashSet<String> hs = new HashSet<>(n);
HashSet<String> hs = HashSet.newHashSet(n);
for (int i = 0; i < n; i++)
hs.add(aliases[i]);
aliasSet = Collections.unmodifiableSet(hs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public final class DecimalStyle {
*/
public static Set<Locale> getAvailableLocales() {
Locale[] l = DecimalFormatSymbols.getAvailableLocales();
Set<Locale> locales = new HashSet<>(l.length);
Set<Locale> locales = HashSet.newHashSet(l.length);
Collections.addAll(locales, l);
return locales;
}
Expand Down
9 changes: 1 addition & 8 deletions src/java.base/share/classes/java/util/Calendar.java
Original file line number Diff line number Diff line change
Expand Up @@ -2640,14 +2640,7 @@ public static Set<String> getAvailableCalendarTypes() {
}

private static class AvailableCalendarTypes {
private static final Set<String> SET;
static {
Set<String> set = new HashSet<>(3);
set.add("gregory");
set.add("buddhist");
set.add("japanese");
SET = Collections.unmodifiableSet(set);
}
private static final Set<String> SET = Set.of("gregory", "buddhist", "japanese");
private AvailableCalendarTypes() {
}
}
Expand Down
25 changes: 25 additions & 0 deletions src/java.base/share/classes/java/util/HashSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,10 @@ public HashSet(Collection<? extends E> c) {
* Constructs a new, empty set; the backing {@code HashMap} instance has
* the specified initial capacity and the specified load factor.
*
* @apiNote
* To create a {@code HashSet} with an initial capacity that accommodates
* an expected number of elements, use {@link #newHashSet(int) newHashSet}.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @throws IllegalArgumentException if the initial capacity is less
Expand All @@ -138,6 +142,10 @@ public HashSet(int initialCapacity, float loadFactor) {
* Constructs a new, empty set; the backing {@code HashMap} instance has
* the specified initial capacity and default load factor (0.75).
*
* @apiNote
* To create a {@code HashSet} with an initial capacity that accommodates
* an expected number of elements, use {@link #newHashSet(int) newHashSet}.
*
* @param initialCapacity the initial capacity of the hash table
* @throws IllegalArgumentException if the initial capacity is less
* than zero
Expand Down Expand Up @@ -372,4 +380,21 @@ public Object[] toArray() {
public <T> T[] toArray(T[] a) {
return map.keysToArray(map.prepareArray(a));
}

/**
* Creates a new, empty HashSet suitable for the expected number of elements.
* The returned set uses the default load factor of 0.75, and its initial capacity is
* generally large enough so that the expected number of elements can be added
* without resizing the set.
*
* @param numElements the expected number of elements
* @param <T> the type of elements maintained by the new set
* @return the newly created set
* @throws IllegalArgumentException if numElements is negative
* @since 19
*/
public static <T> HashSet<T> newHashSet(int numElements) {
return new HashSet<>(HashMap.calculateHashMapCapacity(numElements));
}

}
27 changes: 26 additions & 1 deletion src/java.base/share/classes/java/util/LinkedHashSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ public class LinkedHashSet<E>
* Constructs a new, empty linked hash set with the specified initial
* capacity and load factor.
*
* @apiNote
* To create a {@code LinkedHashSet} with an initial capacity that accommodates
* an expected number of elements, use {@link #newLinkedHashSet(int) newLinkedHashSet}.
*
* @param initialCapacity the initial capacity of the linked hash set
* @param loadFactor the load factor of the linked hash set
* @throws IllegalArgumentException if the initial capacity is less
Expand All @@ -139,6 +143,10 @@ public LinkedHashSet(int initialCapacity, float loadFactor) {
* Constructs a new, empty linked hash set with the specified initial
* capacity and the default load factor (0.75).
*
* @apiNote
* To create a {@code LinkedHashSet} with an initial capacity that accommodates
* an expected number of elements, use {@link #newLinkedHashSet(int) newLinkedHashSet}.
*
* @param initialCapacity the initial capacity of the LinkedHashSet
* @throws IllegalArgumentException if the initial capacity is less
* than zero
Expand Down Expand Up @@ -166,7 +174,7 @@ public LinkedHashSet() {
* @throws NullPointerException if the specified collection is null
*/
public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true);
super(HashMap.calculateHashMapCapacity(Math.max(c.size(), 12)), .75f, true);
addAll(c);
}

Expand All @@ -193,4 +201,21 @@ public LinkedHashSet(Collection<? extends E> c) {
public Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
}

/**
* Creates a new, empty LinkedHashSet suitable for the expected number of elements.
* The returned set uses the default load factor of 0.75, and its initial capacity is
* generally large enough so that the expected number of elements can be added
* without resizing the set.
*
* @param numElements the expected number of elements
* @param <T> the type of elements maintained by the new set
* @return the newly created set
* @throws IllegalArgumentException if numElements is negative
* @since 19
*/
public static <T> LinkedHashSet<T> newLinkedHashSet(int numElements) {
return new LinkedHashSet<>(HashMap.calculateHashMapCapacity(numElements));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ private Builder readModuleAttribute(DataInput in, ConstantPool cpool, int major)

int exports_to_count = in.readUnsignedShort();
if (exports_to_count > 0) {
Set<String> targets = new HashSet<>(exports_to_count);
Set<String> targets = HashSet.newHashSet(exports_to_count);
for (int j=0; j<exports_to_count; j++) {
int exports_to_index = in.readUnsignedShort();
String target = cpool.getModuleName(exports_to_index);
Expand Down Expand Up @@ -486,7 +486,7 @@ private Builder readModuleAttribute(DataInput in, ConstantPool cpool, int major)

int open_to_count = in.readUnsignedShort();
if (open_to_count > 0) {
Set<String> targets = new HashSet<>(open_to_count);
Set<String> targets = HashSet.newHashSet(open_to_count);
for (int j=0; j<open_to_count; j++) {
int opens_to_index = in.readUnsignedShort();
String target = cpool.getModuleName(opens_to_index);
Expand Down Expand Up @@ -540,7 +540,7 @@ private Set<String> readModulePackagesAttribute(DataInput in, ConstantPool cpool
throws IOException
{
int package_count = in.readUnsignedShort();
Set<String> packages = new HashSet<>(package_count);
Set<String> packages = HashSet.newHashSet(package_count);
for (int i=0; i<package_count; i++) {
int index = in.readUnsignedShort();
String pn = cpool.getPackageName(index);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ private static Set<String> schemesListToSet(String list) {
allowRestrictedHeaders = Boolean.parseBoolean(
props.getProperty("sun.net.http.allowRestrictedHeaders"));
if (!allowRestrictedHeaders) {
restrictedHeaderSet = new HashSet<>(restrictedHeaders.length);
restrictedHeaderSet = HashSet.newHashSet(restrictedHeaders.length);
for (int i=0; i < restrictedHeaders.length; i++) {
restrictedHeaderSet.add(restrictedHeaders[i].toLowerCase());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ private static class DefaultOptionsHolder {
static final Set<SocketOption<?>> defaultOptions = defaultOptions();

private static Set<SocketOption<?>> defaultOptions() {
HashSet<SocketOption<?>> set = new HashSet<>(2);
HashSet<SocketOption<?>> set = HashSet.newHashSet(2);
set.add(StandardSocketOptions.SO_RCVBUF);
set.add(StandardSocketOptions.SO_REUSEADDR);
if (Net.isReusePortAvailable()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ private static class DefaultOptionsHolder {
static final Set<SocketOption<?>> defaultOptions = defaultOptions();

private static Set<SocketOption<?>> defaultOptions() {
HashSet<SocketOption<?>> set = new HashSet<>(5);
HashSet<SocketOption<?>> set = HashSet.newHashSet(5);
set.add(StandardSocketOptions.SO_SNDBUF);
set.add(StandardSocketOptions.SO_RCVBUF);
set.add(StandardSocketOptions.SO_KEEPALIVE);
Expand Down
2 changes: 1 addition & 1 deletion src/java.base/share/classes/sun/nio/fs/AbstractPoller.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ final WatchKey register(Path dir,
// validate arguments before request to poller
if (dir == null)
throw new NullPointerException();
Set<WatchEvent.Kind<?>> eventSet = new HashSet<>(events.length);
Set<WatchEvent.Kind<?>> eventSet = HashSet.newHashSet(events.length);
for (WatchEvent.Kind<?> event: events) {
// standard events
if (event == StandardWatchEventKinds.ENTRY_CREATE ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ WatchKey register(final Path path,
throws IOException
{
// check events - CCE will be thrown if there are invalid elements
final Set<WatchEvent.Kind<?>> eventSet = new HashSet<>(events.length);
final Set<WatchEvent.Kind<?>> eventSet = HashSet.newHashSet(events.length);
for (WatchEvent.Kind<?> event: events) {
// standard events
if (event == StandardWatchEventKinds.ENTRY_CREATE ||
Expand Down
2 changes: 1 addition & 1 deletion src/java.base/share/classes/sun/security/pkcs/PKCS7.java
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ public void encodeSignedData(DerOutputStream out)
// CRLs (optional)
if (crls != null && crls.length != 0) {
// cast to X509CRLImpl[] since X509CRLImpl implements DerEncoder
Set<X509CRLImpl> implCRLs = new HashSet<>(crls.length);
Set<X509CRLImpl> implCRLs = HashSet.newHashSet(crls.length);
for (X509CRL crl: crls) {
if (crl instanceof X509CRLImpl)
implCRLs.add((X509CRLImpl) crl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public boolean isForwardCheckingSupported() {
@Override
public Set<String> getSupportedExtensions() {
if (supportedExts == null) {
supportedExts = new HashSet<String>(2);
supportedExts = HashSet.newHashSet(2);
supportedExts.add(BasicConstraints_Id.toString());
supportedExts.add(NameConstraints_Id.toString());
supportedExts = Collections.unmodifiableSet(supportedExts);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ final class ForwardBuilder extends Builder {

// populate sets of trusted certificates and subject DNs
trustAnchors = buildParams.trustAnchors();
trustedCerts = new HashSet<X509Certificate>(trustAnchors.size());
trustedSubjectDNs = new HashSet<X500Principal>(trustAnchors.size());
trustedCerts = HashSet.newHashSet(trustAnchors.size());
trustedSubjectDNs = HashSet.newHashSet(trustAnchors.size());
for (TrustAnchor anchor : trustAnchors) {
X509Certificate trustedCert = anchor.getTrustedCert();
if (trustedCert != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public boolean isForwardCheckingSupported() {
@Override
public Set<String> getSupportedExtensions() {
if (supportedExts == null) {
supportedExts = new HashSet<String>(3);
supportedExts = HashSet.newHashSet(3);
supportedExts.add(KeyUsage_Id.toString());
supportedExts.add(ExtendedKeyUsage_Id.toString());
supportedExts.add(SubjectAlternativeName_Id.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class PolicyChecker extends PKIXCertPathChecker {
if (initialPolicies.isEmpty()) {
// if no initialPolicies are specified by user, set
// initPolicies to be anyPolicy by default
this.initPolicies = new HashSet<String>(1);
this.initPolicies = HashSet.newHashSet(1);
this.initPolicies.add(ANY_POLICY);
} else {
this.initPolicies = new HashSet<String>(initialPolicies);
Expand Down Expand Up @@ -154,7 +154,7 @@ public boolean isForwardCheckingSupported() {
@Override
public Set<String> getSupportedExtensions() {
if (supportedExts == null) {
supportedExts = new HashSet<String>(4);
supportedExts = HashSet.newHashSet(4);
supportedExts.add(CertificatePolicies_Id.toString());
supportedExts.add(PolicyMappings_Id.toString());
supportedExts.add(PolicyConstraints_Id.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ private static Collection<String> getSubjectAltNames(
if ((subAltDnsName != null) && !subAltDnsName.isEmpty()) {
if (subAltDnsNames == null) {
subAltDnsNames =
new HashSet<>(subjectAltNames.size());
HashSet.newHashSet(subjectAltNames.size());
}
subAltDnsNames.add(subAltDnsName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ private static class X509Credentials {
// assert privateKey and certificates != null
this.privateKey = privateKey;
this.certificates = certificates;
this.issuerX500Principals = new HashSet<>(certificates.length);
this.issuerX500Principals = HashSet.newHashSet(certificates.length);
for (X509Certificate certificate : certificates) {
issuerX500Principals.add(certificate.getIssuerX500Principal());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ private InternalLocaleBuilder setExtensions(List<String> bcpExtensions, String p
clearExtensions();

if (!LocaleUtils.isEmpty(bcpExtensions)) {
Set<CaseInsensitiveChar> done = new HashSet<>(bcpExtensions.size());
Set<CaseInsensitiveChar> done = HashSet.newHashSet(bcpExtensions.size());
for (String bcpExt : bcpExtensions) {
CaseInsensitiveChar key = new CaseInsensitiveChar(bcpExt);
// ignore duplicates
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public OpeningHandshake(BuilderImpl b) {
private static Collection<String> createRequestSubprotocols(
Collection<String> subprotocols)
{
LinkedHashSet<String> sp = new LinkedHashSet<>(subprotocols.size(), 1);
LinkedHashSet<String> sp = LinkedHashSet.newLinkedHashSet(subprotocols.size());
for (String s : subprotocols) {
if (s.trim().isEmpty() || !isValidName(s)) {
throw illegal("Bad subprotocol syntax: " + s);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ private static Collection<TCPTransport> allKnownTransports() {
Set<TCPTransport> s;
synchronized (localEndpoints) {
// presize s to number of localEndpoints
s = new HashSet<TCPTransport>(localEndpoints.size());
s = HashSet.newHashSet(localEndpoints.size());
for (LinkedList<TCPEndpoint> epList : localEndpoints.values()) {
/*
* Each local endpoint has its transport added to s.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3309,7 +3309,7 @@ public byte[] comment() {
public Optional<Set<PosixFilePermission>> storedPermissions() {
Set<PosixFilePermission> perms = null;
if (posixPerms != -1) {
perms = new HashSet<>(PosixFilePermission.values().length);
perms = HashSet.newHashSet(PosixFilePermission.values().length);
for (PosixFilePermission perm : PosixFilePermission.values()) {
if ((posixPerms & ZipUtils.permToFlag(perm)) != 0) {
perms.add(perm);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public static void main(String argv[]) throws Exception {

// Prepare to wait for FOS, FD, Cleanup to be reclaimed
ReferenceQueue<Object> queue = new ReferenceQueue<>();
HashSet<Reference<?>> pending = new HashSet<>(3);
HashSet<Reference<?>> pending = HashSet.newHashSet(3);
pending.add(new WeakReference<>(cleanup, queue));
pending.add(new WeakReference<>(raf, queue));
pending.add(new WeakReference<>(fd, queue));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public class TestFileEncoding {
private String expectedEncoding; // Expected value for file.encoding
private String langVar = null; // Value to set for LANG, etc

private static Set<String> envToRm = new HashSet<>(3);
private static Set<String> envToRm = HashSet.newHashSet(3);
static {
// Take these vars out of the test's run environment, possibly adding
// our own value back in.
Expand Down
2 changes: 1 addition & 1 deletion test/jdk/java/text/Format/common/FormatIteratorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ protected String escapeIfNecessary(String string) {
}

public Set<Attribute> makeAttributes(List<Object> names) {
Set<Attribute> set = new HashSet<>(Math.max(1, names.size()));
Set<Attribute> set = HashSet.newHashSet(names.size());

for (int counter = 0; counter < names.size(); counter++) {
set.add(makeAttribute((String)names.get(counter)));
Expand Down
Loading

1 comment on commit e01cd7c

@openjdk-notifier
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.