HashSet get() and contains() methods, by value or reference?

All the tutorials I've seen on HashSets use Strings as the object type. With Strings, it seems the get() and contains() methods work by value, not by reference.
<CODE>
String s1 = "dog";
String s2 = "cat";
String s3 = "dog";
HashSet<String> set = new HashSet<String>();
set.add(s1);
System.out.println(set.contains(s1)); //true;
System.out.println(set.contains(s2)); //false
System.out.println(set.contains(s3)); //true
</CODE>
But when I use a custom object, it works by reference:
<CODE>
MyClass c1 = new MyClass("dog", 1);
MyClass c2 = new MyClass("cat", 1);
MyClass c3 = new MyClass("dog", 2);
MyClass c4 = new MyClass("dog", 1);
HashSet<MyClass> myClassSet = new HashSet<MyClass>();
myClassSet.add(c1);
System.out.println(myClassSet.contains(c1)); //true
System.out.println(myClassSet.contains(c2)); //false
System.out.println(myClassSet.contains(c3)); //false
System.out.println(myClassSet.contains(c4)); //false
</CODE>
("MyClass" is a simple class that holds a String and an int).
Is there any way I can get the set to select by value rather than reference for objects that aren't String?
If so, is it possible that the value test could be customised, so that, for example, the above will return true if the String in MyClass is the same, regardless of the int value?

803559 wrote:
With Strings, it seems the get() and contains() methods work by value, not by reference.
String s1 = "dog";
String s2 = "cat";
String s3 = "dog";
System.out.println(set.contains(s1)); //true;
System.out.println(set.contains(s2)); //false
System.out.println(set.contains(s3)); //true
Is there any way I can get the set to select by value rather than reference for objects that aren't String?Warning: Never use the term "by reference" around Java geeks. It makes 'em go all green at the gills and they start muttering about 'bloody C++ crossovers'.
However, as DrClap pointed out, you've mis-diagnosed the problem:
System.out.println(s1 == s1);
System.out.println(s1 == s2);
System.out.println(s1 == s3));would print out the exact same results.
For an explanation why, Google "Java String pool" or try [url http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal]here.
If so, is it possible that the value test could be customised, so that, for example, the above will return true if the String in MyClass is the same, regardless of the int value?Absolutely. But, as others have said, you'd need to override equals() and hashCode().
Winston

Similar Messages

  • Over riding hashtable get and put method

    Hi all
    Anyone have any idea about over ride HashTable get() and put(). Is it possible to over ride HashTable methods.

    Yes_me wrote:
    I want to change the structure of the java HashTable get and put method. As put method is having two object parameters I want to send one more parameter as String to it. Is it possible to change the structure in this way.What would you want to be returned when calling get()? I would go with the suggestion to create a class to keep that information. If you really want to, you can completely hide that information class inside your extended HashTable. You could create an overloaded put method that takes three parameters and then creates an instance of the information class and put that into the map. If you only want the data for display only, the get method could get the information class mapped to the given key, then simply return a nicely formatted String containing the two values.

  • Code for replacing 'get' and 'set' method

    Hi,
    I was a struts programmer but now i am a jsf programmer :-)
    I was able to do the following with struts but no with jsf...
    The following code in struts allowed me to have no 'get' and 'set' method in the javabean for a property (for example, the property 'name'):
    ValueStack valueStack =ActionContext.getContext().getValueStack();
    valueStack.set("name", "John");
    ActionContext.getContext().setValueStack(valueStack);In the jsp, using the corresponding label to retrieve the 'name' property, returned value 'John'.
    Is there something equivalent in jsf?

    Hi, see on here.There are solutions for JSF, JBoss Seam: [Solutions for Java, JSF, JBoss Seam and Flex|http://flextrick.blogspot.com/]

  • Why do we need get and set methods?

    It is considered good design practice to keep all class data private and
    provide get and set methods for accessing the data in a controlled
    manner.
    So, instead of directly accessing the class data, you use getter and setters.
    I do not really feel the need to use get and set methods.
    How does that achieve encapsulation when ultimately the class data is being exposed?

    A couple of reasons why to use get and set:
    1. For example you can set an int value for month, if a user sets this to somting
    higher than 12 (or 11 if it's zero based) you want to handle that by either
    throwing an exception or adding a year for every time it can be devided by 12.
    If you dont do it in set you'll have a whole bunch of methods that might need to
    correct the value before retreiving the eventual date.
    2. If for some reason you have security set up for certain values you can
    implement this in the get method. When this is done somewhere else you have
    a whole bunch of methods retreiving the info in other classes that need to check
    first. (a canGet method could allso be used). Another good reason to use get
    is when the information needs to be converted depending on the consumer
    calling the get method.
    3. If any logic in 1 or 2 changes you'll have a bunch of code to change.
    If you feel there is no need to implement any security, error handling (on
    compiling because get and set might throw something) or validation when
    setting/getting these values there is still the argument of readabillity.
    Eclipse has a feature that will generate getters and setters for you so it's not
    like there is a lot of extra typing involved.
    Got interupted whyle typig so sorry to repeat any answer given before.

  • QM Module - How to get the Inspection Method & Characteristic value(Urgent)

    Hi All,
        I have inspection lot number (PRUEFLOS), batch number 
       (CHARGE), plant (WERK) & material number
       (MATNR) , using these fields how to get the inspection
       method (PMETHODE) & Characteristic Value (ATWRT) ?
       I don’t know the relation among them.
    Could you please help?
    Thanks in advance.
    Saket

    Hi Jose,
    Thanks for your help, could you please look into my requirement.
    For all inspection characteristics listed in the selected COA profile, I have to retrieve the Inspection Method for all listed inspection characteristics. And also I have to retrieve the characteristic value(uncertainty). Additionally, for inspection characteristics that are quantitative, being checked, the characteristic value(uncertainty) from that Inspection method will be retrieved from class 3050_UNCERTAINTY, class type 006, characteristic, P2150_UNCERTAINTY. 
    Please help me out.
    Thanks,
    Saket .

  • Manager in mate becasue all method get  and not method set???

    In mate they use this technology what I do not still have clear is that because always in the managers methods go only get and not set????? Because??
    [Bindable (event="sqPhotoDBCountChanged")]
            public function get sqPhotoDBCount():uint {
                //trace("PhotoManager.sqPhotoDBCount(), 'sqPhotoDBCount' event response, sqPhotoDBCount = "+_sqPhotoDBCount);
                return _sqPhotoDBCount;
    And not this method set because????????

    In your servlet, you have written doget() method but it should be doGet().

  • Statistical distributions - get and setter methods

    Hi,
    I found the Weibull and Cauchy class here:
    http://commons.apache.org/math/api-1.1/org/apache/commons/math/distribution/CauchyDistributionImpl.html
    however these distributions do not seem to have methods to pick a random number within the distribution.
    Does anyone have any advise on how to do that?
    Thanks,
    Lene

    Ok, I don't see a getNextValue or getNextDouble.
    Did you mean inverseCumulativeProbability?
    I guess I could create a random P and then look up the x at that p, to get a random value from the distribution.
    Thanks,
    Lene

  • Usage of AQ$_JMS_MESSAGE getter and setter methods in PL/SQL functions

    Hi all,
    while setting up a transformation from a AQ$_JMS_TEXT_MESSAGE to a user-defined type "msgtype" ( subject varchar2, text clob ) I tried to use the get_text() method within the transformation function but got a
    ORA-25229: error on transformation of message msgid: ...
    ORA-30625: method dispatch on NULL SELF argument is disallowedAccessing the CLOB part of the jms_text_message directly did not work. But within an anonymous PL/SQL procedure, get_text() works fine.
    It has to be in a function to work as a transformation, but how can I do this?
    Here's my current code:
    CREATE OR REPLACE FUNCTION jms2msg_t(in_jms SYS.AQ$_JMS_TEXT_MESSAGE)
    RETURN TxtMsgType AS
      new_msg  TxtMsgType;
      v_oldmsg SYS.AQ$_JMS_TEXT_MESSAGE;
      v_clob   CLOB := EMPTY_CLOB;
    BEGIN
      dbms_lob.createTemporary( v_clob, true );
      dbms_lob.open( v_clob, DBMS_LOB.LOB_READWRITE );
      v_oldmsg.get_text( v_clob ); -- ora-30625 happens here ----------------
      new_msg := TxtMsgType( dbms_lob.substr( in_jms.text_lob, 10 ), v_clob );
      dbms_lob.freetemporary(lob_loc => v_clob);
      RETURN new_msg;
    END jms2msg_t;
    /MetaLink, Oracle Docs and Google didn't help me. I know of the countermeasures against ORA-30625 in user defined types, but I cannot change JMS-Types, So, what could I do?
    Regards,
    Uwe

    Gee, this was a no-brainer. Thanks to cut w/o paste, I lost the initializing line:
    v_oldmsg:=in_jms;The uninitialized JMS object then throws this kind of "null pointer exception".
    Well, at least I got to know a new ORA-code. ;-)

  • What is get and set methods of class

    I m new for OOP concept see this is my class, How this class will return values???
    package poker
        import com.smartfoxserver.v2.protocol.serialization.SerializableSFSType;
        public class SeatInfo implements SerializableSFSType
            private var _seats:Array;
            private var _buyInLow:int;
            private var _buyInHigh:int;
            public function SeatInfo(){
            public function get seats():Array{
                return _seats;
            public function set seats(seats:Array):void{
                this._seats = seats;           
            public function get buyInLow():int
                return _buyInLow;
            public function set buyInLow(buyInLow:int):void
                this._buyInLow = buyInLow;
            public function get buyInHigh():int
                return _buyInHigh;
            public function set buyInHigh(buyInHigh:int):void
                this._buyInHigh = buyInHigh;
            public function toString():String
                var str:String="seatinfo";
                str += "amtlow" + ": " + _buyInLow + "amthig" + ": " + _buyInHigh + " :\n";
                if (_seats != null)
                    for each (var seat:Seat in _seats)                
                    str += "seat :" + seat.seatId +"\n"   
                return str;

    package poker
        import com.smartfoxserver.v2.protocol.serialization.SerializableSFSType;
        public class SeatInfo implements SerializableSFSType
            private var _seats:Array;
            private var _buyInLow:int;
            private var _buyInHigh:int;
            public function SeatInfo(){
            // this returns _seats
            public function get seats():Array{
                return _seats;
            public function set seats(seats:Array):void{
                this._seats = seats;           
    // this returns _buyinLow
            public function get buyInLow():int
                return _buyInLow;
            public function set buyInLow(buyInLow:int):void
                this._buyInLow = buyInLow;
            // this returns _buyInHight
            public function get buyInHigh():int
                return _buyInHigh;
            public function set buyInHigh(buyInHigh:int):void
                this._buyInHigh = buyInHigh;
            public function toString():String
                var str:String="seatinfo";
                str += "amtlow" + ": " + _buyInLow + "amthig" + ": " + _buyInHigh + " :\n";
                if (_seats != null)
                    for each (var seat:Seat in _seats)                
                    str += "seat :" + seat.seatId +"\n"   
                return str;
    so, in another class where you need those variable values:
    import SeatInfo;
    var seatInfo:SeatInfo;
    var seatsVar:Array;
    var buyInLowVar:int;
    var buyInHighVar:int;
    seatInfo = new SeatInfo();
    seatsVar = seatInfo.seats;
    buyInLowVar = seatInfo.buyInLow;
    buyInHighVar = seatInfo.buyInHigh;

  • Generic Getter and Setters

    Hi all,
    I want to dynamically access getter and setter methods depending on the variables i have
    suppose i have a variable
    String checkGetter;
    and a getter method
    public String getCheckGetter(){return this.checkGetter;}
    and in addition to that some more variables and their getters and setters
    and i want to access all the getter/setter methods dynamically ,if i am having only the variable name(as a String). I dont want to add code for accessing these methods, instead put in a loop and do my work.
    Can one achieve this in Java.
    Thanks in advance.
    Regards.

    neo_java wrote:
    I am just trying to understand if there is any way to assign values to variables where the value to be assigned to the variable depends on run time
    (here the variable is important to me which changes dynamically).Rene's first Law of Anti-Static: every idea including the word "dynamically" can be safely disregarded as foolish.
    You can not assign anything to variables by names. You can assign values to instance or class attributes using Reflection. You can also drive a car backwards all the time. It's awkward, it won't work nicely and it can crash quite quickly. You could also use a map where you store a value assigned to a certain key or name, as already mentioned. Or you could pass the name (why do you have the name in the first place!? No good.) along with the value to the instance and let the instance find out what to do by itself.

  • We are trying to do a Quick payment from payment workbench and getting 'FRM-41830: List of values contains no entries' error for payment document column/field. Payment document setup looks good. Not sure what the issue is.

    We are trying to do a Quick payment from payment workbench and getting 'FRM-41830: List of values contains no entries' error for payment document column/field. Payment document setup looks good. Not sure what the issue is.

    Already gone through following three notes but didn't found resolution.
    APXPAWKB: FRM-41830 When Clicking on Payment Document LOV (Doc ID 1081305.1)
    R12: APXPAWKB: Payment Document Lov Is Empty When Entering A Payment (Doc ID 857587.1)
    R12: Payment Workbench Error: FRM-41830 List Of Values Contains No Entries (APXPAWKB.FMB) (Doc ID 1323875.1)

  • Call C# method from javascript in WebView and retrieve the return value

    The issue I am facing is the following :
    I want to call a C# method from the javascript in my WebView and get the result of this call in my javascript.
    In an WPF Desktop application, it would not be an issue because a WebBrowser
    (the equivalent of a webView) has a property ObjectForScripting to which we can assign a C# object containg the methods we want to call from the javascript.
    In an Windows Store Application, it is slightly different because the WebView
    only contains an event ScriptNotify to which we can subscribe like in the example below :
    void MainPage_Loaded(object sender, RoutedEventArgs e)
    this.webView.ScriptNotify += webView_ScriptNotify;
    When the event ScriptNotify is raised by calling window.external.notify(parameter), the method webView_ScriptNotify is called with the parameter sent by the javascript :
    function CallCSharp() {
    var returnValue;
    window.external.notify(parameter);
    return returnValue;
    private async void webView_ScriptNotify(object sender, NotifyEventArgs e)
    var parameter = e.Value;
    var result = DoSomerthing(parameter);
    The issue is that the javascript only raise the event and doesn't wait for a return value or even for the end of the execution of webView_ScriptNotify().
    A solution to this issue would be call a javascript function from the webView_ScriptNotify() to store the return value in a variable in the javascript and retrieve it after.
    private async void webView_ScriptNotify(object sender, NotifyEventArgs e)
    var parameter = e.Value;
    var result = ReturnResult();
    await this.webView.InvokeScriptAsync("CSharpCallResult", new string[] { result });
    var result;
    function CallCSharp() {
    window.external.notify(parameter);
    return result;
    function CSharpCallResult(parameter){
    result = parameter;
    However this does not work correctly because the call to the CSharpResult function from the C# happens after the javascript has finished to execute the CallCSharp function. Indeed the
    window.external.notify does not wait for the C# to finish to execute.
    Do you have any solution to solve this issue ? It is quite strange that in a Window Store App it is not possible to get the return value of a call to a C# method from the javascript whereas it is not an issue in a WPF application.

    I am not very familiar with the completion pattern and I could not find many things about it on Google, what is the principle? Unfortunately your solution of splitting my JS function does not work in my case. In my example my  CallCSharp
    function is called by another function which provides the parameter and needs the return value to directly use it. This function which called
    CallCSharp will always execute before an InvokeScriptAsync call a second function. Furthermore, the content of my WebView is used in a cross platforms context so actually my
    CallCSharp function more look like the code below.
    function CallCSharp() {
    if (isAndroid()) {
    //mechanism to call C# method from js in Android
    //return the result of call to C# method
    } else if (isWindowsStoreApp()) {
    window.external.notify(parameter);
    // should return the result of call to C# method
    } else {
    In android, the mechanism in the webView allows to return the value of the call to a C# method, in a WPF application also. But I can't figure why for a Windows Store App we don't have this possibility.

  • How can I get the variable with the value from Thread Run method?

    We want to access a variable from the run method of a Thread externally in a class or in a method. Even though I make the variable as public /public static, I could get the value till the end of the run method only. After that scope of the variable gets lost resulting to null value in the called method/class..
    How can I get the variable with the value?
    This is sample code:
    public class SampleSynchronisation
         public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run method "+sathr.x);
    // I should get Inside the run method::: But I get only Inside
    class sampleThread extends Thread
         public String x="Inside";
         public void run()
              x+="the run method";
    NB: if i write the variable in to a file I am able to read it from external method. This I dont want to do

    We want to access a variable from the run method of a
    Thread externally in a class or in a method. I presume you mean a member variable of the thread class and not a local variable inside the run() method.
    Even
    though I make the variable as public /public static, I
    could get the value till the end of the run method
    only. After that scope of the variable gets lost
    resulting to null value in the called method/class..
    I find it easier to implement the Runnable interface rather than extending a thread. This allows your class to extend another class (ie if you extend thread you can't extend something else, but if you implement Runnable you have the ability to inherit from something). Here's how I would write it:
    public class SampleSynchronisation
      public static void main(String[] args)
        SampleSynchronisation app = new SampleSynchronisation();
      public SampleSynchronisation()
        MyRunnable runner = new MyRunnable();
        new Thread(runner).start();
        // yield this thread so other thread gets a chance to start
        Thread.yield();
        System.out.println("runner's X = " + runner.getX());
      class MyRunnable implements Runnable
        String X = null;
        // this method called from the controlling thread
        public synchronized String getX()
          return X;
        public void run()
          System.out.println("Inside MyRunnable");
          X = "MyRunnable's data";
      } // end class MyRunnable
    } // end class SampleSynchronisation>
    public class SampleSynchronisation
    public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run
    method "+sathr.x);
    // I should get Inside the run method::: But I get
    only Inside
    class sampleThread extends Thread
    public String x="Inside";
    public void run()
    x+="the run method";
    NB: if i write the variable in to a file I am able to
    read it from external method. This I dont want to do

  • How can I get the variable with the value from Thread's run method

    We want to access a variable from the run method of a Thread externally in a class or in a method. Even though I make the variable as public /public static, I could get the value till the end of the run method only. After that scope of the variable gets lost resulting to null value in the called method/class..
    How can I get the variable with the value?
    This is sample code:
    public class SampleSynchronisation
         public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run method "+sathr.x);
    /* I should get:
    Inside the run method
    But I get only:
    Inside*/
    class sampleThread extends Thread
         public String x="Inside";
         public void run()
              x+="the run method";
    NB: if i write the variable in to a file I am able to read it from external method. This I dont want to do

    Your main thread continues to run after the sathr thread is completed, consequently the output is done before the sathr thread has modified the string. You need to make the main thread pause, this will allow sathr time to run to the point where it will modify the string and then you can print it out. Another way would be to lock the object using a synchronized block to stop the main thread accessing the string until the sathr has finished with it.

  • Contains Area and Shape method

    Hi,
    I've some problems with the "contains" method of the
    Area class in java.awt.geom...the problem is that the boolean value from this method is always false for me..
    This is the code for a shape object, but the same is for
    an area object. Thank you if you can.
    boolean pippo;
    Ellipse2D.Float circle2;
    circle2 = new Ellipse2D.Float(50,50,50,50);
    pippo= circle2.contains(50,50);
    System.out.println(pippo);

    Did you read the API?
    contains:
    Tests if the interior of this Ellipse2D entirely
    contains the specified rectangular area.
    Maybe it has to do with this - as you are specifying a
    point that is not interior but on the outside edge??
    Therefore it returns false.I'don't think this is the problem...
    the istruction:
         circle2 = new Ellipse2D.Float(50,50,50,50);
    create a circle in position x=50 y=50 with radius=50
    and so the coordinate's point (50,50) should be in any case inside the circle!

Maybe you are looking for