Checking if values are the same

Discussion in 'Java' started by francan00, Oct 28, 2007.

  1. francan00

    francan00 Guest

    I currently have two String objects I check to find out if they are
    the same value:

    String str1 = "red";
    String str2 = "yellow";
    if (str1.equals(str2)){
    System.out.println("Equal");
    }
    else{
    System.out.println("Not equal");
    }


    Now I need to check 10 objects. How would I check 10 objects to find
    out if any of them have the same value?

    Please advise.
     
    francan00, Oct 28, 2007
    #1
    1. Advertisements

  2. francan00

    Are Nybakk Guest

    Couldn't you just iterate through a String array? Or add the Strings to
    two collections and check equality that way?
     
    Are Nybakk, Oct 28, 2007
    #2
    1. Advertisements

  3. francan00

    Lew Guest

    Variations on:

    Collection <Thing> mightHaveDupes = getSomeCollection();
    Collection <Thing> noDupes = new WhateverCollection <Thing> ();
    // we'll get back to which Collection implementation to use

    for ( Thing thing : mightHaveDupes )
    {
    if ( noDupes.contains( thing ))
    {
    log( "Thing {"+ thing +"} is duplicated." );
    }
    else
    {
    noDupes.add( thing );
    }
    }

    If the copy is a Set, then duplication is avoided automatically:

    public <T> boolean hasDupes( Collection<T> mayHave )
    {
    Set<T> copy = new HashSet<T> ( mayHave );
    return (copy.size() < mayHave.size());
    }
     
    Lew, Oct 28, 2007
    #3
  4. francan00

    Daniel Pitts Guest

    The easiest way would probably be to add them to a Set of some sort
    (HashSet probably). Set.add() will return false if that value was
    already in the set.
     
    Daniel Pitts, Oct 28, 2007
    #4
  5. francan00

    francan00 Guest

    Thanks, I dont have Generics in my Java 1.4 environment.

    How would this be without Generics?

    public <T> boolean hasDupes( Collection<T> mayHave )
    {
    Set<T> copy = new HashSet<T> ( mayHave );
    return (copy.size() < mayHave.size());

    }
     
    francan00, Oct 28, 2007
    #5
  6. Just delete all instances of "<T>".

    Patricia
     
    Patricia Shanahan, Oct 28, 2007
    #6
  7. francan00

    Are Nybakk Guest

    I think I misunderstood somewhat - should be one collection and you can
    check if it contains your string.

    Lew's solution, however, is quite elegant.
     
    Are Nybakk, Oct 28, 2007
    #7
  8. francan00

    Roedy Green Guest

    You want an array of Strings. You compare each of them against the
    first one. See http://mindprod.com/jgloss/array.html
     
    Roedy Green, Oct 28, 2007
    #8
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.