下面列出了java.util.HashSet#toArray ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static NetworkInterface[] getNetworkInterfaces() {
final HashSet<NetworkInterface> list = new HashSet<NetworkInterface>();
try {
final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
final NetworkInterface next = interfaces.nextElement();
if (next.supportsMulticast() && next.isUp()) {
list.add(next);
}
}
} catch (SocketException e) {
//Ignore
}
return list.toArray(new NetworkInterface[list.size()]);
}
/**
* Disjunctive license sets can contain other conjunctive license sets as members. Logically,
* the members of these "sub-disjunctive license sets" could be direct members and have the same
* meaning.
* @return all members "flattening out" disjunctive license sets which are members of this set
*/
protected AnyLicenseInfo[] getFlattenedMembers() {
if (this.resource != null && this.refreshOnGet) {
try {
getPropertiesFromModel();
} catch (InvalidSPDXAnalysisException e) {
logger.warn("Error getting properites from model, using stored values.",e);
}
}
HashSet<AnyLicenseInfo> retval = new HashSet<AnyLicenseInfo>(); // Use a set since any duplicated elements would be still considered equal
Iterator<AnyLicenseInfo> iter = this.licenseInfos.iterator();
while (iter.hasNext()) {
AnyLicenseInfo li = iter.next();
if (li instanceof DisjunctiveLicenseSet) {
// we need to flatten this out
AnyLicenseInfo[] members = ((DisjunctiveLicenseSet)li).getFlattenedMembers();
for (int i = 0; i < members.length; i++) {
retval.add(members[i]);
}
} else {
retval.add(li);
}
}
return retval.toArray(new AnyLicenseInfo[retval.size()]);
}
@Test
public void testRemoveRandomly() {
final int COUNT = 100;
Random rand = new Random();
DynamicValueSortedTreeMap<String, Integer> queue = new DynamicValueSortedTreeMap<>();
HashSet<String> all = new HashSet<>();
for (int i = 0; i < COUNT; i++) {
queue.put("Element" + i, rand.nextInt(50));
all.add("Element" + i);
}
checkConsistent(queue);
String[] shuffled = all.toArray(new String[all.size()]);
for (int i = 0; i < shuffled.length; i++) {
ArrayUtils.swap(shuffled, i, i + rand.nextInt(shuffled.length - i));
}
for (String s : shuffled) {
queue.remove(s);
checkConsistent(queue);
}
assertTrue(queue.isEmpty());
assertTrue(queue.size() == 0);
}
/**
* Returns an array of all parameter names defined as part of this web request.
* @since 1.3.1
**/
public String[] getRequestParameterNames() {
final HashSet names = new HashSet();
ParameterProcessor pp = new ParameterProcessor() {
public void addParameter( String name, String value, String characterSet ) throws IOException {
names.add( name );
}
public void addFile( String parameterName, UploadFileSpec fileSpec ) throws IOException {
names.add( parameterName );
}
};
try {
_parameterHolder.recordPredefinedParameters( pp );
_parameterHolder.recordParameters( pp );
} catch (IOException e) {}
return (String[]) names.toArray( new String[ names.size() ] );
}
public ConfigDataImpl(List<ConfigItem> configItems) {
ArrayList<ConfigItemImpl> cis = new ArrayList<ConfigItemImpl>(configItems.size());
HashSet<String> sourceSet = new HashSet<String>();
for (ConfigItem configItem : configItems) {
if (configItem != null) {
cis.add((ConfigItemImpl)configItem.copy());
if (configItem.getSource() != null && !"UNKNOWN".equals(configItem.getSource())) {
sourceSet.add(configItem.getSource());
}
totalConfigItems++;
if (configItem.isRegistered()) {
registeredConfigItems++;
} else {
unRegisteredConfigItems++;
}
}
}
this.sources = sourceSet.toArray(new String[sourceSet.size()]);
Collections.sort(cis);
this.items = new ArrayList<ConfigItem>(cis);
}
public String[] getPropertyGroups(String prefix) {
Enumeration keys = props.propertyNames();
HashSet groups = new HashSet(10);
if (!prefix.endsWith(".")) {
prefix += ".";
}
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
if (key.startsWith(prefix)) {
String groupName = key.substring(prefix.length(), key.indexOf(
'.', prefix.length()));
groups.add(groupName);
}
}
return (String[]) groups.toArray(new String[groups.size()]);
}
public String[] getPropertyGroups(String prefix) {
Enumeration keys = props.propertyNames();
HashSet groups = new HashSet(10);
if (!prefix.endsWith(".")) {
prefix += ".";
}
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
if (key.startsWith(prefix)) {
String groupName = key.substring(prefix.length(), key.indexOf(
'.', prefix.length()));
groups.add(groupName);
}
}
return (String[]) groups.toArray(new String[groups.size()]);
}
private static <S extends ImageReaderWriterSpi>
String[] getReaderWriterInfo(Class<S> spiClass, SpiInfo spiInfo)
{
// Ensure category is present
Iterator<S> iter;
try {
iter = theRegistry.getServiceProviders(spiClass, true);
} catch (IllegalArgumentException e) {
return new String[0];
}
HashSet<String> s = new HashSet<String>();
while (iter.hasNext()) {
ImageReaderWriterSpi spi = iter.next();
Collections.addAll(s, spiInfo.info(spi));
}
return s.toArray(new String[s.size()]);
}
/**
* Searches all property keys that start with a given prefix.
*
* @param prefix the prefix that all selected property keys should share
* @return the properties as iterator.
*/
public Iterator<String> findPropertyKeys( final String prefix ) {
if ( prefix == null ) {
throw new NullPointerException( "Prefix must not be null" );
}
final HashSet<String> keys = new HashSet<String>();
collectPropertyKeys( prefix, this, keys );
final String[] objects = keys.toArray( new String[ keys.size() ] );
Arrays.sort( objects );
return Arrays.asList( objects ).iterator();
}
private String[] generateAccounts()
{
String[] result = new String[25];
HashSet set = new HashSet();
while(set.size() < result.length)
{
set.add("788000"+(int)(10+Math.random()*90)+"01");
}
set.toArray(result);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
HashSet<X509Certificate> issuers=new HashSet<X509Certificate>();
for (X509TrustManager mgr : managers) {
for (X509Certificate cert : mgr.getAcceptedIssuers()) {
issuers.add(cert);
}
}
return(issuers.toArray(new X509Certificate[issuers.size()]));
}
@Override
public ICompilationUnit[] getAffectedCompilationUnits(final RefactoringStatus status, ReferencesInBinaryContext binaryRefs, IProgressMonitor pm) throws CoreException {
IMethod method= (IMethod)fMethodBinding.getJavaElement();
Assert.isTrue(method != null);
SearchPattern pattern= SearchPattern.createPattern(method, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
IJavaSearchScope scope= RefactoringScopeFactory.create(method, true, false);
final HashSet<ICompilationUnit> affectedCompilationUnits= new HashSet<ICompilationUnit>();
CollectingSearchRequestor requestor= new CollectingSearchRequestor(binaryRefs) {
private ICompilationUnit fLastCU;
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (filterMatch(match))
return;
if (match.isInsideDocComment())
return; // TODO: should warn user (with something like a ReferencesInBinaryContext)
ICompilationUnit unit= SearchUtils.getCompilationUnit(match);
if (match.getAccuracy() == SearchMatch.A_INACCURATE) {
if (unit != null) {
status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match,
JavaStatusContext.create(unit, new SourceRange(match.getOffset(), match.getLength())));
} else {
status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match);
}
} else if (unit != null) {
if (! unit.equals(fLastCU)) {
fLastCU= unit;
affectedCompilationUnits.add(unit);
}
}
}
};
new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, new SubProgressMonitor(pm, 1));
return affectedCompilationUnits.toArray(new ICompilationUnit[affectedCompilationUnits.size()]);
}
public String[] getLocations() throws IOException {
HashSet<String> hostSet = new HashSet<String>();
for (Path file : getPaths()) {
FileSystem fs = file.getFileSystem(getJob());
FileStatus status = fs.getFileStatus(file);
BlockLocation[] blkLocations = fs.getFileBlockLocations(status,
0, status.getLen());
if (blkLocations != null && blkLocations.length > 0) {
addToSet(hostSet, blkLocations[0].getHosts());
}
}
return hostSet.toArray(new String[hostSet.size()]);
}
public EstimatedParameter[] getAllParameters() {
HashSet<EstimatedParameter> set = new HashSet<EstimatedParameter>();
for (int i = 0; i < measurements.length; ++i) {
EstimatedParameter[] parameters = measurements[i].getParameters();
for (int j = 0; j < parameters.length; ++j) {
set.add(parameters[j]);
}
}
return set.toArray(new EstimatedParameter[set.size()]);
}
@Override
public String[] getPlatformFontNames() {
HashSet<String> nameSet = new HashSet<String>();
FcFontManager fm = (FcFontManager) fontManager;
FontConfigManager fcm = fm.getFontConfigManager();
FcCompFont[] fcCompFonts = fcm.loadFontConfig();
for (int i=0; i<fcCompFonts.length; i++) {
for (int j=0; j<fcCompFonts[i].allFonts.length; j++) {
nameSet.add(fcCompFonts[i].allFonts[j].fontFile);
}
}
return nameSet.toArray(new String[0]);
}
/**
*
* @param comps Isotope composition of an isotope pattern in the format [13]C[37]Cl[13]C
* @return Array of all occurring isotopes within comp
*/
public static String[] getIsotopesFromComposition(String[] comps) {
HashSet<String> set = new HashSet<>();
for (String comp : comps) {
// the elements are allocated between ] [ e.g.: [13]C[37]Cl[13]C
String[] isotopes = comp.split(Pattern.quote("["));
for (String isotope : isotopes) {
isotope = StringUtils.stripEnd(isotope, "0123456789");
set.add("[" + isotope);
}
}
set.remove("["); // gets added by default due to split, removing should be faster than a check
return set.toArray(new String[0]);
}
@Test
public void testAllocateAndRecycle() {
RecyclingIntBlockAllocator allocator = newAllocator();
HashSet<int[]> allocated = new HashSet<>();
int[] block = allocator.getIntBlock();
allocated.add(block);
assertNotNull(block);
final int size = block.length;
int numIters = atLeast(97);
for (int i = 0; i < numIters; i++) {
int num = 1 + random().nextInt(39);
for (int j = 0; j < num; j++) {
block = allocator.getIntBlock();
assertNotNull(block);
assertEquals(size, block.length);
assertTrue("block is returned twice", allocated.add(block));
assertEquals(4 * size * (allocated.size() + allocator.numBufferedBlocks()), allocator
.bytesUsed());
}
int[][] array = allocated.toArray(new int[0][]);
int begin = random().nextInt(array.length);
int end = begin + random().nextInt(array.length - begin);
List<int[]> selected = new ArrayList<>();
for (int j = begin; j < end; j++) {
selected.add(array[j]);
}
allocator.recycleIntBlocks(array, begin, end);
for (int j = begin; j < end; j++) {
assertNull(array[j]);
int[] b = selected.remove(0);
assertTrue(allocated.remove(b));
}
}
}
public String[] getLocations() throws IOException {
HashSet<String> hostSet = new HashSet<String>();
for (Path file : getPaths()) {
FileSystem fs = file.getFileSystem(getJob());
FileStatus status = fs.getFileStatus(file);
BlockLocation[] blkLocations = fs.getFileBlockLocations(status,
0, status.getLen());
if (blkLocations != null && blkLocations.length > 0) {
addToSet(hostSet, blkLocations[0].getHosts());
}
}
return hostSet.toArray(new String[hostSet.size()]);
}
@Override
public String[] getDnsServerAddresses() {
try {
Process process = Runtime.getRuntime().exec("getprop");
InputStream inputStream = process.getInputStream();
LineNumberReader lnr = new LineNumberReader(
new InputStreamReader(inputStream));
String line;
HashSet<String> server = new HashSet<>(6);
while ((line = lnr.readLine()) != null) {
int split = line.indexOf("]: [");
if (split == -1) {
continue;
}
String property = line.substring(1, split);
String value = line.substring(split + 4, line.length() - 1);
if (value.isEmpty()) {
continue;
}
if (property.endsWith(".dns") || property.endsWith(".dns1") ||
property.endsWith(".dns2") || property.endsWith(".dns3") ||
property.endsWith(".dns4")) {
// normalize the address
InetAddress ip = InetAddress.getByName(value);
if (ip == null) continue;
value = ip.getHostAddress();
if (value == null) continue;
if (value.length() == 0) continue;
server.add(value);
}
}
if (server.size() > 0) {
return server.toArray(new String[server.size()]);
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Exception in findDNSByExec", e);
}
return null;
}
static public String[] getWordsInStringWithBigrams(String inputText,
boolean useStemming) {
// remove URLs, rt @username, and a bunch of special characters
String text = inputText;
text = text.toLowerCase();
String regexp = "(^|\\s)rt\\s|@\\S+|http\\S+|www\\.\\S+|[-.,;:_+?&=\"*~¨^´`<>\\[\\]{}()\\\\/|%€¤$£@!§½…]"; //
text = text.replaceAll(regexp, "");
String[] words = text.split("\\s+");
// Stem words
if (useStemming) {
for (int i = 0; i < words.length; i++) {
words[i] = naiveStemming(words[i]);
}
}
// Make bigrams
HashSet<String> bigrams = new HashSet<String>();
// remove single quotes from word's beginning and end
for (int index = 0; index < words.length; index ++) {
words[index] = words[index].replaceAll(SINGLE_QUOTE_PATTERN_AT_EXTREME,"");
}
for (int i = 0; i < words.length - 1; i++) {
String w1 = words[i];
if (isStopword(w1)) {
continue;
}
String w2 = "";
int j = i + 1;
while (j < words.length && isStopword(w2 = words[j])) {
j++;
}
// Perform stopword removal
if (!isStopword(w2)) {
bigrams.add(w1 + "_" + w2);
}
}
bigrams.addAll(Arrays.asList(words));
if (bigrams.isEmpty()) {
return new String[0];
} else {
return bigrams.toArray(new String[bigrams.size()]);
}
}