Equals() in Sets and Collections

It is a common knowledge that Collection per se are not supposed to have equals() method: first, comparing two bags (multisets) is too costly, second, comparing a Collection to a List may lead to ignoring the List order - the same elements but in different order is a different List, right?
Then I have a question: why does SortedSet have equals() method? It is definitely not just a Map, but a decorator; the order can be different. It is obviously an error.
Unlike the other clumsy feature:
Map<String> m1 = new HashMap();
Map<String> m2 = new HashMap();
m1.put("k", "v");
m2.put("k", "v");
m1.equals(m2); // returns true
m1.values().equals(m2.values()); // returns false - there is a long explanation why
Another, unrelated, observation.
String[] a1 = new String[] {"a", "b"};
String[] a2 = new String[] {"a", "b"};
a1.equals(a2); // returns false - bad, bad, bad implementation!
Arrays.asList(a1).equals(Arrays(asList(a2)); // returns true - way to go!

In which case my response is: It is?I think so. I can't say I've taken a survey, but I doubt that it's "common knowledge" that collections shouldn't override equals.
Otherwise you would end up comparing
Lists and Sets.Not if you follow the documented contracts.
the List order - the same elements but indifferent
order is a different List, right?List's equals contract requires that equals return
true iff the other object is also List and hasthe
same elements (by the elements' equals methods) in
the same order. You are repeating my explanation, are not you?No. I'm pointing out what you seem to have missed--that if you follow the documented contracts, there won't be a problem.
If you're aware of that and I missed you point, perhaps you could try to clarify what you're getting at?
Then I have a question: why does SortedSet have
equals() method? It is definitely not just aMap,
but
a decorator; the order can be different. It is
obviously an error.Set's equals contract only requires that the other
object also be a Set and that the two Sets contain
the same elements. Wrong. I mean, an ordered set is not equivalent to a
set. In your mind it is not. In the view taken by the collections framework, it can be. Neither view is inherently correct or wrong. I've never been in a situation to compare a SortedSet to a non-sorted Set (as far as I know), but I have compared Sets, and my own needs didn't care whether neither, one, or both of the Sets was sorted. So in the cases where I've compared Sets, the current definition has worked for me. I suppose there are cases where it doesn't work.
It has an additional structure: the order. Two
different ordered sets can have the same elements, it
does not mean they are the same. There's nothing inherent about equals() that says it has to compare every attribute or every structural aspect of the objects being compared.
It's math.But this is Java, which is intended to model certain mathematical concepts to a certain degree, but not necessarily to be perfectly faithful to them.
>
>
I suppose you could argue that for
SortedSets, order should matter for equality, buta)
I don't see any real benefit to it and b) You then
wouldn't be able to compare SortedSets to otherSets,
so the specific implementation would matter(unlike
for Maps and Lists).Well, here we are getting closer to the paradox. Of
course it would be interesting to compare SortedSets
as if they were ordinary Sets, and compare them to
Sets as well.As I said, I haven't knowingly done so, but I was glad that I didn't have to care whether they were sorted.
How about Lists? We may be interested in comparing
them too, ignoring the order. A List is an ordered
multiset. Why not compare Lists and Sets, as
Collections? I would not object - but the problem
lies somewhere deeper. Do you know where?I don't know that there is a problem. I'm not saying the current equals contracts are perfect, or that an objective "best" contract can be defined. But in my experience they have served well whenever I've needed them. I think they're a reasonable, practical compromise.
Weird. What is that explanation?values() returns a virtual Collection, a view that
has only an iterator which scans EntrySet and returns
Map.Entry.getValue().Okay. Still not sure why that would return false, but I'm not able to focus on it that much at the moment.
Yeah, I always thought it was odd that arrays'equals
methods didn't behave more like List's. I imagine
there's a reason for it, owing to how the array
classes are created, but still...What could be the reason? I'm just curious, that's
why I started this philosophical thread. :)I don't know, but one thing that's odd about arrays. There's no such class as MyClass[] until I create MyClass. Then MyClass[] magically comes into existence (or maybe the first time I use it). That makes the array classes different from other classes. I imagine it would have been possible to have them provide their own equals() that compares elements, but presumably it was deemed more difficult or complex or error-prone than the perceived value it would add.

Similar Messages

  • Ordering of Collection Sets and Collections (inside Collection Sets)?

    What are the rules for how elements (specifically, collections and other collection sets) are ordered within a collection set?
    I was trying to get a collection to appear at the top of the list of items in a collection set, but it seems to get stuffed below all the other collection sets regardless of the name given to the collection.
    -Strathglass

    Collection Set / Smart Collections / Collections (Alphabetical in each case)
    The same applies inside a Collections Set.
    So a collection will never appear above a smart collection or collection set regardles of it name. If you create a Collection Set then create two Sets within (01, 02) Set 01 could contain Collections and thereby would appear above smart collections in set 02.

  • Dragging folders to create a set and collections?

    I know I can drag folders onto the collections tab to create a collection, but it flattens all the subfolders. Is there a way to drag a folder with subfolders and create collections in a collection set?
    If it helps, an example is that sometimes I may be moving folders to another location and a different structure, and before I do so I want to preserve that folder structure in a collection set.

    robgendreau wrote:
    Does it only do the entire folder tree?
    Yes.
    A logical place to add the feature you want is in the Collection Agent plugin, which has similar features already for duplicating collection sets etc.. - would you use it if it had such a feature? Note: it won't be as slick as drag n' drop - You'd have to select the parent folder, invoke a function to record, then select the position where collection set will need to be, and invoke another function to create. And it may not be obvious how to do all that without reading the instructions.. i.e. klunky, but if it's something you do often, it would be easier than creating manually..

  • Package variable g_security_group_id must be set and Collections

    we have an app that works fine under an individual user schema/workspace. I exported/imported the app into a new workspace/schema and all is well except for the page that is using a collection. when I call this page, it is throwing a 404 error. when I look in the apache error log I see:
    mod_plsql: ORA-20001 Execute ORA-20001: Package variable g_security_group_id must be set.\nORA-06512: at "APEX_030200.F", line 279\nORA-06512: at line 33
    Is there some security setting that needs to be set for the schema/workspace where the app was imported into? This appears to be only a collection issue as the new pages in the imported app work fine except for this one. Any ideas about fixing this g_security_group_id or is there a workaround?
    Thanks.

    Another follow up from me. Mine started with a HTTP 404, so in SQL*Plus:
    exec dbms_epg.set_dad_attribute('APEX','error-style','DebugStyle');I refreshed the page and "ORA-20001: Package variable g_security_group_id must be set" appeared with all the debug info.
    It turned out to be a varchar definition in a package function that was too small for the text I was assigning to it.
    Fixed that, then
    exec dbms_epg.delete_dad_attribute('APEX','error-style');to turn debug off.

  • Object and reference accessing for primitives, objects and collections

    Hi,
    I have questions re objects, primitives and collection accessing and references
    I made a simple class
    public class SampleClass {
         private String attribute = "default";
         public SampleClass()
         public SampleClass(SampleClass psampleClass)
              this.setAttribute(psampleClass.getAttribute());
              if (this.getAttribute() == psampleClass.getAttribute())
                   System.out.println("INSIDE CONSTRUCTOR : same object");
              if (this.getAttribute().equals(psampleClass.getAttribute()))
                   System.out.println("INSIDE CONSTRUCTOR : equal values");
         public void setAttribute(String pattribute)
              this.attribute = pattribute;
              if (this.attribute == pattribute)
                   System.out.println("INSIDE SETTER : same object");
              if (this.attribute.equals(pattribute))
                   System.out.println("INSIDE SETTER : equal values");
         public String getAttribute()
              return this.attribute;
         public static void main(String[] args) {
    ...and another...
    public class SampleClassUser {
         public static void main(String[] args) {
              SampleClass sc1 = new SampleClass();
              String test = "test";
              sc1.setAttribute(new String(test));
              if (sc1.getAttribute() == test)
                   System.out.println("SampleClassUser MAIN : same object");
              if (sc1.getAttribute().equals(test))
                   System.out.println("SampleClassUser MAIN : equal values");
              SampleClass sc2 = new SampleClass(sc1);
              sc1.setAttribute("test");
              if (sc2.getAttribute() == sc1.getAttribute())
                   System.out.println("sc1 and sc2 : same object");
              if (sc2.getAttribute().equals(sc1.getAttribute()))
                   System.out.println("sc1 and sc2 : equal values");
    }the second class uses the first class. running the second class outputs the following...
    INSIDE SETTER : same object
    INSIDE SETTER : equal values
    SampleClassUser MAIN : equal values
    INSIDE SETTER : same object
    INSIDE SETTER : equal values
    INSIDE CONSTRUCTOR : same object
    INSIDE CONSTRUCTOR : equal values
    INSIDE SETTER : same object
    INSIDE SETTER : equal values
    sc1 and sc2 : equal values
    ...i'm just curios why the last 3 lines are the way they are.
    INSIDE SETTER : same object
    INSIDE SETTER : equal values
    sc1 and sc2 : equal values
    how come while inside the setter method, the objects are the same object, and after leaving the setter method are not the same objects?
    Can anyone point a good book that shows in detail how objects, primitives and collections are referenced, especially when passed to methods. Online reference is preferred since the availability of books can be a problem for me.
    Thanks very much

    You are confusing references with objects.
    This compares two object references:
    if( obj1 == obj2 ) { // ...Whereas this compares two objects:
    if( obj1.equals(obj2) ) { // ...A reference is a special value which indicates where in memory two objects happen to be. If you create two strings with the same value they won't be in the same place in memory:
    String s1 = new String("MATCHING");
    String s2 = new String("MATCHING");
    System.out.println( s1 == s2 ); // false.But they do match:
    System.out.println( s1.equals(s2) ); // trueIf you're using a primitive then you're comparing the value that you're interested in. E.g.
    int x = 42;
    int y = 42;
    System.out.println(x == y); // trueBut if you're comparing references you're usually more interested in the objects that they represent that the references themselves.
    Does that clarify matters?
    Dave.

  • How do find Oustanding Sales Report and Collection Report for A/R Invoice

    Dear All,
                     I need to find the Sales Outstanding amount and Collection details like Check or Cash Or RTGS this is including A/R Invoice Amount and JE Pending Amount. Is it possible?
    Kindly any body let me know some idea or if any sql query, plz send me.
    Advance Thanks to all.
    Regards,
    A. Anvar

    Hi!
    Check this, with little modification you can get the report i think
    Declare @FromDate as Datetime
    Declare @ToDate as Datetime
    SET @FromDate = (Select Min(S0.TaxDate) from ORCT S0 where S0.TaxDate >='20110201')
    SET @ToDate = (Select Max(S1.TaxDate) from ORCT S1 Where S1.TaxDate < ='20110228')
    Select R0.TaxDate,R0.Docnum,R0.CardCode,
    'Cash' [Payment Mode],R0.CashSum [Amount]  from ORCT R0
    Where
    R0.TaxDate >=@FromDate and R0.TaxDate <=@ToDate   and R0.Canceled = 'N'
    Union All
    Select R0.TaxDate,R0.Docnum,R0.CardCode,
    'Cheque' [Payment Mode],R0.CheckSum  [Amount]  from ORCT R0
    Where
    R0.TaxDate >=@FromDate and R0.TaxDate <=@ToDate  and R0.Canceled = 'N'
    Union All
    Select R0.TaxDate,R0.Docnum,R0.CardCode,
    'Discount' [Payment Mode],R0.TrsfrSum  [Amount] from ORCT R0
    Where
    R0.TaxDate >=@FromDate and R0.TaxDate <=@ToDate and R0.Canceled = 'N'

  • How the freight cost are transferred from condition type of shipment cost document to service entry sheet and collected in service PO item

    Dear Experts:
    could you please share with me the knowledge for below topic:
    How the freight cost are transferred from condition type of shipment cost document to service entry sheet and collected in service PO item, because these three objects use three different pricing procedures, and different condition type.
    how did the condition type of service entry sheet know to copy the value of whcih condition type in the pricing procedure of shipment cost document?
    Is this SAP standard function OR there need an enhancement to do that?
    I didn’t find related condition value copy setting in background, could you please share related setting with me? Thank you very much for your kind help!
    Best regards,
    Andy

    Hi, Gopi,
    Glad to see your feedback, but i still have question on your feedback:
    which condition type in the pricing procedure of service entry sheet should know to capture the net value of shipment cost doc? becasue there are so many condition types,
    And i have checked the corresponding condition type (PRSX) of service entry sheet pricing procedure in my SAP system, this is a self-defined condition type, but NO any calculation routine maintained for the condition type (PRSX), how did the condition type (PRSX) know to copy the total cost of shipment cost document?
    Below is the example and another question:
    what the relationship between the pricing procedures at service PO item level and service line item level?
    1. The freight cost in shipment cost document—including used condition type and pricing procedure
    The pricing procedure of shipment cost document
    2. The freight cost in service entry sheet—including used condition type and pricing procedure
    The pricing procedure of service entry sheet--the pricing procedure at service line item level
    3. The freight cost in service PO item—including used condition type and pricing procedure:

  • Set inside a Set and powerset problem. Need help.

    I've done other posts about this but I figured I'd start a new thread since I changed it so much. I understand the idea of power sets but not how it needs to be a Set inside a set and also how to get this thing to run. If anyone could show me a power set generator or help me fix my code I'd really appreciate it.
    Thanks in advance
    public static <E> Set<Set <E>> generatePowerSet(Set<E> S){
              Set<E> newSet = new HashSet<E>();
              Set<E> temp = new HashSet<E>();
              if (S.isEmpty() || S.equals("")) {
                   Set<E> emptySet = new HashSet<E>(S);
                   return (Set<Set<E>>) emptySet;
              else {
                   Iterator<E> iter = S.iterator();
                   temp = S;
                   while (iter.hasNext()) {
                        E obj = iter.next();
                        temp.remove(obj);
                        Set<E> P = new HashSet<E>(temp);
                        P.addAll(temp);
                        newSet.addAll(P);
                        return newSet;
              }

    I have no idea what a "power set" is.
    But, this line:
    if (S.isEmpty() || S.equals("")) {should just be:
    if (S.isEmpty()) {S is the input parameter, and is a Set. Therefore, S can never equal an empty string.
    Did you see my reply to your previous thread?
    http://forum.java.sun.com/thread.jspa?threadID=677353
    It seems that you didn't, because you didn't respond to it, and because your current code has the same problem.

  • Merging a set and hashmap

    Hi Guys,
    I have a set in which I store some unique userdefined objects,say a "Color" object.
    So my collection set will look as follows:
    set<Color> objects.
    For example:-
    (color1)
    (color2)
    (color3)
    (color4)
    (color5)
    (color6)
    (color7)
    (color8)
    (color9)
    (color10)
    I also have a HashMap which stores objects as follows:
    HashMap<Color,Color> objects(Also userdefined "Color" objects).
    For example:-
    (color1,color20)
    (color2,color21)
    (color3,color22)
    (color4,color23)
    (color4,color24)
    (color5,color25)
    My need is that I want to merge this set and hashmap so that the resulting collection looks as follows:
    (color1,color20)
    (color2,color21)
    (color3,color22)
    (color4,color23)
    (color4,color24)
    (color5,color25)
    (color6,null)
    (color7,null)
    (color8,null)
    (color9,null)
    (color10,null)
    How could this be achieved.
    Any help is appreciated.
    Thanks....
    P

    Hi,
    I do not understand what problem you are actually facing: if you manage to have your map of five items, then creating a map of ten items should be no problem.
    Bye.

  • Regarding Set and SortedSet

    In the collection API, SortedSet implements Collection and Set interfaces. Why does it implement Collection when Set is already a subclass of Collection ?

    in your first post, you said
    In the collection API, SortedSet implements Collection and Set interfaces. Why does it
    implement Collection when Set is already a subclass of Collection ?Set interface extends Collection...
    SortedSet interface extends Set and it is not implementing Collection.
    here is the title of the SoretedSet interface (javadoc 1.5):
    java.util
    Interface SortedSet<E>
    All Superinterfaces:
        Collection<E>, Iterable<E>, Set<E>
    All Known Implementing Classes:
        TreeSet SortedSet inherits Collection methods by Set interface...

  • Possible bug with Pick flag and Collections

    Odd behaviours in v3.3  (Windows) with pick flags in Collections:
    Create (or use) a Collection Set which contains a number of different collections
    Assign Pick plag to one photo in each collection
    Bug 1: Highlight Collection Set and note that none of the images shows the Pick Flag in the thumbnail view. Also Filtering this view with Pick flag fails to pick up the Flagged images
    Now return to one of the Collections within the Set and create a Virtual Copy of one of the images that has a Pick flag. (Note virtual copy does not have a flag - which seems logical). Return to Collection Set and (Bug 2) note that Pick flag has disappeared from original image and now appears on Virtual copy.
    Something wrong here somewhere I suspect.

    lightshop wrote:
    Odd behaviours in v3.3  (Windows) with pick flags in Collections:
    Create (or use) a Collection Set which contains a number of different collections
    Assign Pick plag to one photo in each collection
    Bug 1: Highlight Collection Set and note that none of the images shows the Pick Flag in the thumbnail view. Also Filtering this view with Pick flag fails to pick up the Flagged images
    Now return to one of the Collections within the Set and create a Virtual Copy of one of the images that has a Pick flag. (Note virtual copy does not have a flag - which seems logical). Return to Collection Set and (Bug 2) note that Pick flag has disappeared from original image and now appears on Virtual copy.
    Something wrong here somewhere I suspect.
    I could partially repeat bug 2.
    I have Collection Set (Test) which contain to collections: "Collection 1" and "Collection 2". Both Collections contain 4 images.
    I selected "Collection 1" and applied Pick flag to all those images. When I select Test (Collection Set) I got 8 images shown,  which none had flags. Ok, this works as expected. I selected "Collection 1" and then selected 1 image and made Virtual copy from it. Lr show me now 4 images with Flag and 1 virtual copy without. Again, works as expected. I now select Test (Collection Set) and I get 9 images (as expected), but one of them, the virtual copy, has pick flag applied. Not as expected. If I go back to "Collection 1" I get four images with Pick flags and one virtual copy without. (as expected.)

  • Distribute and Collect BPC NW 7.0

    Hi,
        I'm trying to test distribute and collect functionality in BPC 7.0. I was able to distribute reports to network drives. I was getting blank workbook without data. Any prerequisite for Workbook or report settings for distribute other than Password???
        1. Save workbook as "Live" and lock the Work Book.
        2. Set Worksheet Password to WB
        3. Upload saved workbook into app server.
        4. develop Distribute list using New list option from eTools.
        5. distribute workbook or report using "Distribute & Collect Offline Wizard".
       Made sure Marco security settings as per the requirement. File got created in the network folder. But, File created with NO DATA. Expansion and VAR Keys working great. NO DATA populated.
        Can any one of you help me to fix my problem.
    Thanks,
    Ben.

    No CE 7.1 is not sufficient.  You need NW 7.0 + Enh1.
    Best regards,
    [Jeffrey Holdeman|https://www.sdn.sap.com/irj/sdn/wiki?path=/display/profile/jeffrey+holdeman]
    Enterprise Performance Management
    Regional Implementation Group

  • BT Box Sets and BT Film - what's on?

    Hi,
    I used to subscribe to BT Vision, and am now considering BT TV.
    The wife is quite interested to know what she will be able to watch from BT Box Sets and Film, but I'm unable to find out! The BT TV website has this to say if you click the link "explore Film and TV Box sets" -
    "Film & TV Box Sets
    Film and TV on demand. Unlimited access to US and UK box sets and a large range of films. Watch dramas, comedies, documentaries and cinematic modern greats whenever you want."
    Not exactly enlightening then! So I thought I'd ask here, as you good people are users of the service... What's on Box Sets and Film? I'm thinking the answer may be 'not much' since it's impossible to track down the info at www.bt.com !
    Thanks in advance for any help :-)

    Jiust had a look for you for one of the categories - tv box sets :
    The following are available as at 28 April for a fee of £1.10 per episode or with an extra tv subscription.
    Mr Sunshine  S 1
    Sherlock  S1 and S2
    New Tricks S10
    Breaking In S1 S2
    Flash Forward S1
    Call The Midwife S1 S2
    Kyle XY S1 to S4
    Franklin and bash S1
    Gavin & Stacey S1 to S3
    Lucan S1
    The Killiing S1
    The Attenborough Collection (lots of different documentaries)
    The River S1
    The Bridge S1
    Lost Girl  S1 S2
    Detroit 187 S1
    Zero Hour S1
    Scandal  S1 S2
    Ajmerica's next top model S18
    Desperate Housewives S1 to S8
    Mad Love S1
    The Returned S1
    Torchwood S1 to S3
    Revenge S1 S2
    Luther S1 S2
    Criminal Minds S1 - 9
    Da Vincis Demons S1
    Justified S1 to s3
    Gavin Stacey S1 to S3
    Outnumbered S1 S2
    Extras S1 S2
    Dexter S7
    Castle S1 to S5
    GCB S1
    Hustle S8
    Wildlife collection
    Devious Maids S1
    Pan Am S1
    Being Human USA S1
    Miistresses S1
    Tje Paradise S1
    Criime   infcl NCIS
    Once upon a time S1 S2
    Spiral S4
    Extras S1 S2
    The office S1 S2
    I have the £5 per month subscription for 12 months with my YouView box, but haven't signed up to pay for extra content as I don't want to pay more and I don't have Infinity anyway, only ADSL,
    Note - when I click on these titles, I get two messages.
    a) I need to go to bt.com to add the title to my subscription
    b) Rent SD £1.1O   per episode 
    I don't know how miuch it costs for the extra channel subscription.
    Also - licences expire at intervals so you by the time you get your YouView box, if you buy one, some of these titles might no longer be available......

  • Set and HashSet

    Below is the snippet copied from collection framework tutorial
    import java.util.*;
    public class SetExample {
    public static void main(String args[]) {
    Set set = new HashSet();
    set.add("Bernadine");
    set.add("Elizabeth");
    set.add("Gene");
    set.add("Elizabeth");
    set.add("Clara");
    System.out.println(set);
    Set sortedSet = new TreeSet(set);
    System.out.println(sortedSet);
    My question is Why people like to use "Set set = new HashSet();" rather that "HashSet set = new HashSet();" Both work well
    Is there a difference between them?
    Or just the coding convention nothing else
    I believe Set set = new HashSet() woule be better cause it comes from SUN official tutorial
    thanks

    Set set = new HashSet();Allows for an easy change to work with another kind of Set later on.
    Since the set-variable is set to be a Set, only the actual methods which are
    available in Set will be used by the programmer and thus the type of
    set can still be changed later on by changing the construction of the set and
    not changing anything else in the code.
    Set set = new SortedSet();This rule applies to all possible objects which have a relation to an interface.
    The actual rule says: use the most generic interface available and possible.
    So whenever you would be relying on specific features of for instance the hashSet,
    you shouldn't use this form, but use
    HashSet set = new HashSet();This is only an example, since I honestly have no idea why anyone would ever use specific
    features of a HashSet (and if such features even exist).
    But this example can be valid in other situations.
    kind regards,

  • Form distribution and collection by e-mail alone?

    I am trying to set up an automated system for data collection via Acrobat-generated forms.  But, the respondents are in rural Africa and  have at best lousy internet access and can barely manage e-mail.  Do the form distribution and collection functions of Acrobat work when using e-mail back and forth alone, or is a connection to Acrobat.com required?
    Thanks

    Yes, it can work if the forms are sent by email. The idea is they are sent to you, and you use Acrobat to add them to Tracker. Or you can not use Tracker and just manage the data yourself.

Maybe you are looking for