Java Code Examples for java.util.Set#equals()

The following examples show how to use java.util.Set#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RepositoryWildcardTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanQuery(MBeanServer mbs,
                              String name,
                              Set<ObjectName> expectedSet)
    throws Exception {
    int error = 0;
    System.out.println("Test: queryNames(" + name + ")");
    Set<ObjectName> returnedSet =
            mbs.queryNames(ObjectName.getInstance(name), null);
    System.out.println("ReturnedSet = " + new TreeSet(returnedSet));
    System.out.println("ExpectedSet = " + new TreeSet(expectedSet));
    if (returnedSet.equals(expectedSet)) {
        System.out.println("Test passed!");
    } else {
        error++;
        System.out.println("Test failed!");
    }
    return error;
}
 
Example 2
Source File: Clipboard.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Checks change of the <code>DataFlavor</code>s and, if necessary,
 * notifies all listeners that have registered interest for notification
 * on <code>FlavorEvent</code>s.
 *
 * @since 1.5
 */
private void fireFlavorsChanged() {
    if (flavorListeners == null) {
        return;
    }
    Set<DataFlavor> prevDataFlavors = currentDataFlavors;
    currentDataFlavors = getAvailableDataFlavorSet();
    if (prevDataFlavors.equals(currentDataFlavors)) {
        return;
    }
    FlavorListener[] flavorListenerArray =
            (FlavorListener[])flavorListeners.getListenersInternal();
    for (int i = 0; i < flavorListenerArray.length; i++) {
        final FlavorListener listener = flavorListenerArray[i];
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                listener.flavorsChanged(new FlavorEvent(Clipboard.this));
            }
        });
    }
}
 
Example 3
Source File: AbstractCompletePrefixUnfolding.java    From codebase with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean isHealthyCutoffEvent(E event) {
	E corr = this.getCorrespondingEvent(event);
	if (corr==null) return false;
	
	Set<C> ecs = new HashSet<C>(event.getLocalConfiguration().getCut());
	Set<C> ccs = new HashSet<C>(corr.getLocalConfiguration().getCut());
	
	ecs.removeAll(event.getPostConditions());
	ccs.removeAll(corr.getPostConditions());
	
	if (ecs.equals(ccs)) 
		return true;
	
	return false;
}
 
Example 4
Source File: Preference.java    From ticdesign with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to persist a set of Strings to the {@link android.content.SharedPreferences}.
 * <p>
 * This will check if this Preference is persistent, get an editor from
 * the {@link PreferenceManager}, put in the strings, and check if we should commit (and
 * commit if so).
 *
 * @param values The values to persist.
 * @return True if the Preference is persistent. (This is not whether the
 *         value was persisted, since we may not necessarily commit if there
 *         will be a batch commit later.)
 * @see #getPersistedStringSet(Set)
 *
 * @hide Pending API approval
 */
protected boolean persistStringSet(Set<String> values) {
    if (shouldPersist()) {
        // Shouldn't store null
        if (values.equals(getPersistedStringSet(null))) {
            // It's already there, so the same as persisting
            return true;
        }

        SharedPreferences.Editor editor = mPreferenceManager.getEditor();
        editor.putStringSet(mKey, values);
        tryCommit(editor);
        return true;
    }
    return false;
}
 
Example 5
Source File: EqualsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    boolean test;

    /* synchronizedList test */
    List list = Collections.synchronizedList(new ArrayList());
    list.add(list);
    test = list.equals(list);
    assertTrue(test);
    list.remove(list);

    /* synchronizedSet test */
    Set s = Collections.synchronizedSet(new HashSet());
    s.add(s);
    test = s.equals(s);
    assertTrue(test);

    /* synchronizedMap test */
    Map m =  Collections.synchronizedMap(new HashMap());
    test = m.equals(m);
    assertTrue(test);

}
 
Example 6
Source File: AnnotationsOnModules.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    ModuleElement m1 = processingEnv.getElementUtils().getModuleElement("m1x");
    Set<String> actualAnnotations = new HashSet<>();
    Set<String> expectedAnnotations =
            new HashSet<>(Arrays.asList("@m1x.A", "@java.lang.Deprecated", "@m1x.C({@m1x.E, @m1x.E})"));

    for (AnnotationMirror am : m1.getAnnotationMirrors()) {
        actualAnnotations.add(am.toString());
    }

    if (!expectedAnnotations.equals(actualAnnotations)) {
        throw new AssertionError("Incorrect annotations: " + actualAnnotations);
    }

    return false;
}
 
Example 7
Source File: RepositoryWildcardTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static int mbeanQuery(MBeanServer mbs,
                              String name,
                              Set<ObjectName> expectedSet)
    throws Exception {
    int error = 0;
    System.out.println("Test: queryNames(" + name + ")");
    Set<ObjectName> returnedSet =
            mbs.queryNames(ObjectName.getInstance(name), null);
    System.out.println("ReturnedSet = " + new TreeSet(returnedSet));
    System.out.println("ExpectedSet = " + new TreeSet(expectedSet));
    if (returnedSet.equals(expectedSet)) {
        System.out.println("Test passed!");
    } else {
        error++;
        System.out.println("Test failed!");
    }
    return error;
}
 
Example 8
Source File: VisibilityLabelsCache.java    From hbase with Apache License 2.0 6 votes vote down vote up
public List<String> getGroupAuths(String[] groups) {
  this.lock.readLock().lock();
  try {
    List<String> auths = EMPTY_LIST;
    Set<Integer> authOrdinals = getGroupAuthsAsOrdinals(groups);
    if (!authOrdinals.equals(EMPTY_SET)) {
      auths = new ArrayList<>(authOrdinals.size());
      for (Integer authOrdinal : authOrdinals) {
        auths.add(ordinalVsLabels.get(authOrdinal));
      }
    }
    return auths;
  } finally {
    this.lock.readLock().unlock();
  }
}
 
Example 9
Source File: ReadData.java    From swift-k with Apache License 2.0 6 votes vote down vote up
private String[] readStructHeader(Type type, BufferedReader br, Node owner, 
        Map<String, Object> opts) throws IOException {
	String line = br.readLine();
	if (line == null) {
		throw new ExecutionException(owner, "Missing header");
	}
	else {
	    String sep = getOption("separator", opts);
		String[] header = split(line, sep, owner);
		Set<String> t = new HashSet<String>(type.getFieldNames());
		Set<String> h = new HashSet<String>(Arrays.asList(header));
		if (t.size() != h.size()) {
			throw new ExecutionException(owner, "File header does not match type. " + "Expected "
					+ t.size() + " whitespace separated items. Got " + h.size() + " instead.");
		}
		if (!t.equals(h)) {
			throw new ExecutionException(owner, "File header does not match type. "
					+ "Expected the following whitespace separated header items: " + t
					+ ". Instead, the header was: " + h);
		}
		return header;
	}
}
 
Example 10
Source File: ConfigXMLReader.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
static AttributesSpec getSpec(String mode, Set<String> includeAttributes, Set<String> excludeAttributes) {
    if ("messages".equals(mode)) {
        if (includeAttributes == null && excludeAttributes == null) {
            return EVENT_MESSAGES;
        }
        // SPECIAL: here, include messages plus/minus extras
        Set<String> includeAttr = new HashSet<>(EventUtil.getEventErrorMessageAttrNames());
        if (includeAttributes != null) {
            includeAttr.addAll(includeAttributes);
        }
        if (excludeAttributes != null) {
            includeAttr.removeAll(excludeAttributes);
        }
        if (includeAttr.equals(EventUtil.getEventErrorMessageAttrNames())) { // avoid needless copies
            return EVENT_MESSAGES;
        }
        return new IncludeAttributesSpec(includeAttr);
    } else if (includeAttributes != null || "none".equals(mode)) {
        // whitelist mode
        if (includeAttributes != null && !includeAttributes.isEmpty()) {
            // none plus extras
            return new IncludeAttributesSpec(includeAttributes);
        }
        return NONE;
    } else {
        if (excludeAttributes != null && !excludeAttributes.isEmpty()) {
            // blacklist mode
            return new ExcludeAttributesSpec(excludeAttributes);
        }
        return ALL;
    }
}
 
Example 11
Source File: GraphOutputFormatter.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an equivalence relation for nodes in the specified graph.
 *
 * <p>Two nodes are considered equal iff they have equal topology (predecessors and successors).
 *
 * TODO(bazel-team): Make this a method of Digraph.
 */
@SuppressWarnings("ReferenceEquality")
private static <LABEL> EquivalenceRelation<Node<LABEL>> createEquivalenceRelation() {
  return new EquivalenceRelation<Node<LABEL>>() {
    @Override
    public int compare(Node<LABEL> x, Node<LABEL> y) {
      if (x == y) {
        return 0;
      }

      if (x.numPredecessors() != y.numPredecessors()
          || x.numSuccessors() != y.numSuccessors()) {
        return -1;
      }

      Set<Node<LABEL>> xpred = new HashSet<>(x.getPredecessors());
      Set<Node<LABEL>> ypred = new HashSet<>(y.getPredecessors());
      if (!xpred.equals(ypred)) {
        return -1;
      }

      Set<Node<LABEL>> xsucc = new HashSet<>(x.getSuccessors());
      Set<Node<LABEL>> ysucc = new HashSet<>(y.getSuccessors());
      if (!xsucc.equals(ysucc)) {
        return -1;
      }

      return 0;
    }
  };
}
 
Example 12
Source File: UpdateUserCommand.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param rolesIn The roles to set.
 */
public void setTemporaryRoles(Set<Role> rolesIn) {
    if (!rolesIn.equals(user.getRoles())) {
        rolesChanged = true;
        needsUpdate = true;
        temporaryRoles = rolesIn;
    }
}
 
Example 13
Source File: KeyStatementSupport.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected KeyEffectiveStatement createEmptyEffective(
        final StmtContext<Set<QName>, KeyStatement, KeyEffectiveStatement> ctx, final KeyStatement declared) {
    final Set<QName> arg = ctx.coerceStatementArgument();
    return arg.equals(declared.argument()) ? new EmptyLocalKeyEffectiveStatement(declared)
            : new EmptyForeignKeyEffectiveStatement(declared, arg);
}
 
Example 14
Source File: GeneralizedExternalProcessor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
		public void meet(Join node) {

            Set<QueryModelNode> eSet = getQNodes(node);

            if (eSet.containsAll(sSet) && !(node.getRightArg() instanceof BindingSetAssignment)) {

//                System.out.println("Eset is " + eSet + " and sSet is " + sSet);

                if (eSet.equals(sSet)) {
                    node.replaceWith(set);
                    indexPlaced = true;
                    return;
                } else {
                    if (node.getLeftArg() instanceof StatementPattern && sSet.size() == 1) {
                        if(sSet.contains(node.getLeftArg())) {
                            node.setLeftArg(set);
                            indexPlaced = true;
                        } else if(sSet.contains(node.getRightArg())) {
                            node.setRightArg(set);
                            indexPlaced = true;
                        } else {
                            return;
                        }
                    }
                    else {
                        super.meet(node);
                    }
                }
            } else if (eSet.containsAll(sSet)) {

                super.meet(node);

            } else {
                return;
            }

        }
 
Example 15
Source File: SequenceMachine.java    From htm.java-examples with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Add spatial noise to each pattern in the sequence.
 * 
 * @param sequence      List of patterns
 * @param amount        Amount of spatial noise
 * @return  Sequence with noise added to each non-empty pattern
 */
public List<Set<Integer>> addSpatialNoise(List<Set<Integer>> sequence, double amount) {
    List<Set<Integer>> newSequence = new ArrayList<Set<Integer>>();
    
    for(Set<Integer> pattern : sequence) {
        if(!pattern.equals(NONE)) {
            pattern = patternMachine.addNoise(pattern, amount);
        }
        newSequence.add(pattern);
    }
    
    return newSequence;
}
 
Example 16
Source File: SyntaxProjectsManager.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<FileSystemWatcher> registerWatchers() {
	logInfo(">> registerFeature 'workspace/didChangeWatchedFiles'");
	if (JavaLanguageServerPlugin.getPreferencesManager().getClientPreferences().isWorkspaceChangeWatchedFilesDynamicRegistered()) {
		IPath[] sources = new IPath[0];
		try {
			sources = listAllSourcePaths();
		} catch (JavaModelException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
		}
		List<FileSystemWatcher> fileWatchers = new ArrayList<>();
		Set<String> patterns = new LinkedHashSet<>(basicWatchers);
		patterns.addAll(Stream.of(sources).map(ResourceUtils::toGlobPattern).collect(Collectors.toList()));

		for (String pattern : patterns) {
			FileSystemWatcher watcher = new FileSystemWatcher(pattern);
			fileWatchers.add(watcher);
		}

		if (!patterns.equals(watchers)) {
			JavaLanguageServerPlugin.logInfo(">> registerFeature 'workspace/didChangeWatchedFiles'");
			DidChangeWatchedFilesRegistrationOptions didChangeWatchedFilesRegistrationOptions = new DidChangeWatchedFilesRegistrationOptions(fileWatchers);
			JavaLanguageServerPlugin.getInstance().unregisterCapability(Preferences.WORKSPACE_WATCHED_FILES_ID, Preferences.WORKSPACE_WATCHED_FILES);
			JavaLanguageServerPlugin.getInstance().registerCapability(Preferences.WORKSPACE_WATCHED_FILES_ID, Preferences.WORKSPACE_WATCHED_FILES, didChangeWatchedFilesRegistrationOptions);
			watchers.clear();
			watchers.addAll(patterns);
		}

		return fileWatchers;
	}

	return Collections.emptyList();
}
 
Example 17
Source File: ParticipantsConsistencyChecker.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  logger.debug("Participant consistency checker is initiated. Participants count = {}", participants.size());
  try {
    // when code reaches here, it means there are at least two participants.
    ClusterParticipant clusterParticipant = participants.get(0);
    Set<String> sealedReplicas1 = new HashSet<>(clusterParticipant.getSealedReplicas());
    Set<String> stoppedReplicas1 = new HashSet<>(clusterParticipant.getStoppedReplicas());
    for (int i = 1; i < participants.size(); ++i) {
      logger.debug("Checking sealed replica list");
      Set<String> sealedReplicas2 = new HashSet<>(participants.get(i).getSealedReplicas());
      if (!sealedReplicas1.equals(sealedReplicas2)) {
        logger.warn("Mismatch in sealed replicas. Set {} is different from set {}", sealedReplicas1, sealedReplicas2);
        metrics.sealedReplicasMismatchCount.inc();
      }
      logger.debug("Checking stopped replica list");
      Set<String> stoppedReplicas2 = new HashSet<>(participants.get(i).getStoppedReplicas());
      if (!stoppedReplicas1.equals(stoppedReplicas2)) {
        logger.warn("Mismatch in stopped replicas. Set {} is different from set {}", stoppedReplicas1,
            stoppedReplicas2);
        metrics.stoppedReplicasMismatchCount.inc();
      }
    }
  } catch (Throwable t) {
    logger.error("Exception occurs when running consistency checker ", t);
  }
}
 
Example 18
Source File: TestElementsAnnotatedWith.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations,
                       RoundEnvironment roundEnvironment) {
    TypeElement annotatedElementInfoElement =
        elements.getTypeElement("AnnotatedElementInfo");
    Set<? extends Element> resultsMeta = Collections.emptySet();
    Set<? extends Element> resultsBase = Collections.emptySet();

    if (!roundEnvironment.processingOver()) {
        testNonAnnotations(roundEnvironment);

        // Verify AnnotatedElementInfo is present on the first
        // specified type.

        TypeElement firstType = typesIn(roundEnvironment.getRootElements()).iterator().next();

        AnnotatedElementInfo annotatedElementInfo = firstType.getAnnotation(AnnotatedElementInfo.class);

        boolean failed = false;

        if (annotatedElementInfo == null)
            throw new IllegalArgumentException("Missing AnnotatedElementInfo annotation on " +
                                              firstType);
        else {
            // Verify that the annotation information is as
            // expected.

            Set<String> expectedNames = new HashSet<String>(Arrays.asList(annotatedElementInfo.names()));

            resultsMeta =
                roundEnvironment.
                getElementsAnnotatedWith(elements.getTypeElement(annotatedElementInfo.annotationName()));

            if (!resultsMeta.isEmpty())
                System.err.println("Results: " + resultsMeta);

            if (resultsMeta.size() != annotatedElementInfo.expectedSize()) {
                failed = true;
                System.err.printf("Bad number of elements; expected %d, got %d%n",
                                  annotatedElementInfo.expectedSize(), resultsMeta.size());
            } else {
                for(Element element : resultsMeta) {
                    String simpleName = element.getSimpleName().toString();
                    if (!expectedNames.contains(simpleName) ) {
                        failed = true;
                        System.err.println("Name ``" + simpleName + "'' not expected.");
                    }
                }
            }
        }

        resultsBase = computeResultsBase(roundEnvironment, annotatedElementInfo.annotationName());

        if (!resultsMeta.equals(resultsBase)) {
            failed = true;
            System.err.println("Base and Meta sets unequal;\n meta: " + resultsMeta +
                               "\nbase: " + resultsBase);
        }

        if (failed) {
            System.err.println("AnnotatedElementInfo: " + annotatedElementInfo);
            throw new RuntimeException();
        }
    } else {
        // If processing is over without an error, the specified
        // elements should be empty so an empty set should be returned.
        resultsMeta = roundEnvironment.getElementsAnnotatedWith(annotatedElementInfoElement);
        resultsBase = roundEnvironment.getElementsAnnotatedWith(AnnotatedElementInfo.class);
        if (!resultsMeta.isEmpty())
            throw new RuntimeException("Nonempty resultsMeta: " + resultsMeta);
        if (!resultsBase.isEmpty())
            throw new RuntimeException("Nonempty resultsBase: " + resultsBase);

    }
    return true;
}
 
Example 19
Source File: Sets.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Returns an unmodifiable <b>view</b> of the symmetric difference of two
 * sets. The returned set contains all elements that are contained in either
 * {@code set1} or {@code set2} but not in both. The iteration order of the
 * returned set is undefined.
 *
 * <p>Results are undefined if {@code set1} and {@code set2} are sets based
 * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
 * and the keySet of an {@code IdentityHashMap} all are).
 *
 * @since 3.0
 */


public static <E> SetView<E> symmetricDifference(
  final Set<? extends E> set1, final Set<? extends E> set2) {
  checkNotNull(set1, "set1");
  checkNotNull(set2, "set2");
  return new SetView<E>() {
    @Override
    public Iterator<E> iterator() {
      final Iterator<? extends E> itr1 = set1.iterator();
      final Iterator<? extends E> itr2 = set2.iterator();
      return new AbstractIterator<E>() {
        @Override
        public E computeNext() {
          while (itr1.hasNext()) {
            E elem1 = itr1.next();
            if (!set2.contains(elem1)) {
              return elem1;
            }
          }

          while (itr2.hasNext()) {
            E elem2 = itr2.next();
            if (!set1.contains(elem2)) {
              return elem2;
            }
          }
          return endOfData();
        }
      };
    }

    @Override
    public int size() {
      return Iterators.size(iterator());
    }

    @Override
    public boolean isEmpty() {
      return set1.equals(set2);
    }

    @Override
    public boolean contains(Object element) {
      return set1.contains(element) ^ set2.contains(element);
    }
  };
}
 
Example 20
Source File: CompositeDataSupport.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private CompositeDataSupport(
        SortedMap<String, Object> items, CompositeType compositeType)
        throws OpenDataException {

    // Check compositeType is not null
    //
    if (compositeType == null) {
        throw new IllegalArgumentException("Argument compositeType cannot be null.");
    }

    // item names defined in compositeType:
    Set<String> namesFromType = compositeType.keySet();
    Set<String> namesFromItems = items.keySet();

    // This is just a comparison, but we do it this way for a better
    // exception message.
    if (!namesFromType.equals(namesFromItems)) {
        Set<String> extraFromType = new TreeSet<String>(namesFromType);
        extraFromType.removeAll(namesFromItems);
        Set<String> extraFromItems = new TreeSet<String>(namesFromItems);
        extraFromItems.removeAll(namesFromType);
        if (!extraFromType.isEmpty() || !extraFromItems.isEmpty()) {
            throw new OpenDataException(
                    "Item names do not match CompositeType: " +
                    "names in items but not in CompositeType: " + extraFromItems +
                    "; names in CompositeType but not in items: " + extraFromType);
        }
    }

    // Check each value, if not null, is of the open type defined for the
    // corresponding item
    for (String name : namesFromType) {
        Object value = items.get(name);
        if (value != null) {
            OpenType<?> itemType = compositeType.getType(name);
            if (!itemType.isValue(value)) {
                throw new OpenDataException(
                        "Argument value of wrong type for item " + name +
                        ": value " + value + ", type " + itemType);
            }
        }
    }

    // Initialize internal fields: compositeType and contents
    //
    this.compositeType = compositeType;
    this.contents = items;
}