HashCode function in Object class.

Hi! to all!
I have got a confusion about hashCode function of Object class, which returns an integer.
What is the real purpose of introducing this method in Object class.
Please comment.

hashCode() method of the object is intorduced for the benefit of collections like HashTables. Typically
hashCode method should return distinct integers for distinct objects which are decided distinct based on
equals method of the object. Though this is not mandatory , if distinct objects have distinct
hashCodes, it will improve the performance of HashTables.A good distribution of hash codes will indeed help in the performance of a HashMap or Hashtable. However, by definition, hashcodes are not necessarily distinct for objects that are distinct based on equals. Two objects for which "equals" is true should have the same hashcode, but two objects which have the same hashcode don't have to have "equals" be true. There is a limited number of hashcodes (the range of int), but an unlimited number of objects. So, some objects will necessarily have the same hashcode. The pigeonhole principle describes this situation:
http://en.wikipedia.org/wiki/Pigeonhole_principle

Similar Messages

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • Why methods equals() and hashCode() is defined in Object Class?

    Why methods equals() and hashCode() is defined in Object Class?

    If you have two objects and you don't know (or care about) their exact types, but you still want to know if they are the same, then you can do something like this:
    Object o1 = getObject1();
    Object o2 = getObject2();
    if (o1.equals(o2)) {
      // they are the same, do something
    } else {
      // they are different, do something else
    }This could be useful if you were to write a generic cache, for example.
    A similar thing is true for hashCode(), if you want to manage things in a HashSet, you'll need them to implement hashCode().
    If Object didn't have those methods, then you'd have to write that code against a more specific interface/class and it wouldn't be so general any more.

  • How can i watch native code for hashCode() in Object class?

    How can i watch native code for hashCode() in Object class?

    Those are two different requirements. You still haven't told us why you want the first one.
    The second one is called JNI - Java Native Interface. There is a forum here, and a large amount of documentation, and a book about it.

  • About hashCode() function..

    What is the use of hashCode() function.
    It is in both String and Hashtable classes...
    What is the necessity having same function in both classes..
    What actually it returns...
    Can we use it with any type objects?

    I hope everybody know that java have special
    treatment for Strings.
    int hash1 = "ABCDEa123abc".hashCode();
    int hash2 = "ABCDFB123abc".hashCode();Both the time the string used "ABCDEa123abc" will
    have the same reference. You are trying to make a valid point, but you missed the fact that those two strings are not equal, but produce the same hashCode(). This happens, because you are mapping a large value space (Strings) to a much smaller space (int).
    It's used to demonstrate that you must not depend on the hashCode beeing unique.
    >
    Thats why u always get the same hashcode.

  • How to implement hashCode() function

    Hello everybody
    I need to overrided hashCode method in my Object. This contains 4 attributes of type Long. I need to implement compatible hash code for my equals function.
    public class MyObject {
    Long attr1;
    Long attr2;
    Long attr3;
    Long attr4;
    public boolean equals(Object obj) {
    if (this == obj)
    return true;
    if (this == null || this.getClass() != obj.getClass())
    return false;
    TSCObject object = (TSCObject) obj;
    return (this.attr1 != null && this.attr1.equals(object) &&
    this.attr2 != null &&
    this.attr2.equals(object) &&
    this.attr3 != null && this.attr3.equals(object) &&
    this.attr4 != null &&
    this.attr4.equals(object));
    public int hachCode() {
    return 0;//??????????????
    Can somebody help me. I've heard something about HashCodeBuilder
    Thank

    It is hashCode(), not hachCode().
    You can consider to return the sum of the attr1.hashCode() + attr2.hashCode() + etc. You should try to "guarantee" as much as possible that the hashCode() returns an unique identifier of the MyObject in such a fast way so that it will improve performance of hashmaps/sets/tables which are used to store those objects. If you put a new MyObject in such a hashmap/set/table then it will check based on the hashcode if the object doesn't already exist. If it does, then it will invoke the equals() to check if they are certainly equal (which is generally more expensive).
    Also see http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode()

  • The Object Class

    Hi all,
    I come from a C background and am trying to learn JAVA. I was wondering if the type Object was like a void ptr in C.
    example :
    Object oref;

    My C is fairly limited, but from memory a void pointer is just a pointer that is not currently assigned to "point" to anything. This is not the same as an Object type in Java.
    Object is the root class for everything in Java. So if you write your own class, it will automatically extend Object (maybe not immediately, but somewhere in the hierachy a Class will extend from Object).
    Object provides some useful functionality that all classes therefore have, such as toString() and hashCode()
    Normally, when writing Java, you would not decalre something of type Object, as it would usually be some more specific Sub-Class

  • How to load function from derived class from dll

    Dear all,
    how to access extra function from derived class.
    for Example
    //==========================MyIShape.h
    class CMyIShape
    public:
    CMyIShape(){};
    virtual ~CMyIShape(){};
    virtual void Fn_DrawMe(){};
    // =========== this is ShapRectangle.dll
    //==========================ShapRectangle .h
    #include "MyIShape.h"
    class DLL_API ShapRectangle :public CMyIShape
    public:
    ShapRectangle(){};
    virtual ~ShapRectangle(){};
    virtual void Fn_DrawMe(){/*something here */};
    virtual void Fn_ChangeMe(){/*something here */};
    __declspec (dllexport) CMyIShape* CreateShape()
    // call the constructor of the actual implementation
    CMyIShape * m_Obj = new ShapRectangle();
    // return the created function
    return m_Obj;
    // =========== this is ShapCircle .dll
    //==========================ShapCircle .h
    #include "MyIShape.h"
    class DLL_API ShapCircle :public CMyIShape
    public:
    ShapCircle(){};
    virtual ~ShapCircle(){};
    virtual void Fn_DrawMe(){/*something here */};
    virtual void Fn_GetRadious(){/*something here */};
    __declspec (dllexport) CMyIShape* CreateShape()
    // call the constructor of the actual implementation
    CMyIShape * m_Obj = new ShapCircle();
    // return the created function
    return m_Obj;
    in exe there is no include header of of ShapCircle and ShapRectangle 
    and from the exe i use LoadLibrary and GetProcAddress .
    typedef CMyIShape* (*CREATE_OBJECT) ();
    CMyIShape*xCls ;
    //===================== from ShapeCircle.Dll
    pReg=  (CREATE_OBJECT)GetProcAddress (hInst ,"CreateShape");
    xCls = pReg();
    now xCls give all access of base class. but how to get pointer of funciton Fn_GetRadious() or how to get access.
    thanks in advance.

    could you please tell me in detail. why so. or any reference for it. i love to read.
    i don't know this is bad way.. but how? i would like to know.
    I indicated in the second sentence. Classes can be implemented differently by different compilers. For example, the alignment of member variables may differ. Also there is the pitfall that a class may be allocated within the DLL but deallocated in the client
    code. But the allocation/deallocation algorithms may differ across different compilers, and certainly between DEBUG and RELEASE mode. This means that you must ensure that if the DLL is compiled in Visual Studio 2010 / Debug mode, that the client code is also
    compiled in Visual Studio 2010 / Debug mode. Otherwise your program will be subject to mysterious crashes.
    is there any other way to archive same goal?
    Of course. DLL functionality should be exposed as a set of functions that accept and return POD data types. "POD" means "plain-ole-data" such as long, wchar_t*, bool, etc. Don't pass pointers to classes. 
    Obviously classes can be implemented within the DLL but they should be kept completely contained within the DLL. You might, for example, expose a function to allocate a class internally to the DLL and another function that can be called by the client code
    to free the class. And of course you can define other functions that can be used by the client code to indirectly call the class's methods.
    and why i need to give header file of ShapCircle and shapRectangle class, even i am not using in exe too. i though it is enough to give only MyIShape.h so with this any one can make new object.
    Indeed you don't have to, if you only want to call the public properties and methods that are defined within MyIShape.h.

  • How to create object class for a z table

    Hi All,
    I have a z table and I want to register the changes of fields should be logged to CDHDR and CDPOS table.
    Is this possible?
    If yes how can I creat an object class for a z table. I have already checked the change document option in z data element.
    Please help.
    Regards,
    Jeetu
    Moderator message: standard functionality, please search for available information/documentation before asking.
    locked by: Thomas Zloch on Oct 6, 2010 6:16 PM

    Tcode SCDO. You'll need to create a change document for you Z table and then use the FM created to record the changed data.

  • Using predefined data objects classes.

    I am always trying to be a better, more efficient Flex developer and I was looking at a project by Christophe Coenraets where he created collaberative forms using Flex/BlazeDS. I saw in his application that he was using multidirectional binding to a Class Object for each form in the application. For example, this is the MortgageApplication.as
    package
        import mx.collections.ArrayCollection;
        [Bindable]
        public class MortgageApplication
            public var firstName:String;
            public var lastName:String;
            public var ssn:String;
            public var phone:String;
            public var mobilePhone:String;
            public var email:String;
            public var notify:Boolean;
            public var usCitizen:Boolean;
            public var address:String
            public var city:String
            public var state:String
            public var zip:String
            public var singleFamily:Boolean;
            public var salePrice:Number = 500000;
            public var downPayment:Number = 100000;
            public var closingDate:Date;
            public var jobList:ArrayCollection = new ArrayCollection();
    I have an application that I use multiple forms to input information into the database and then I use Objects (actually ObjectProxys) and ArrayCollections to store information to display. I use the Mate Framework and have manager classes that store predefined bindable variables (empty)  that are injected into the view as needed or requested. In the manager class I just create a new ObjectProxy (or ArrayCollection) and use the information passed in (an ArrayCollection from ColdFusion) and create/modify the ObjectProxy/ArrayCollection before having it injected.
    Is it better practice or more efficent to predefine object classes (such as above from the example) then just populate them in the manager class before the injection or just create an new blank Object or ArrayCollection on the fly. Is there any difference?
    Set up a seperate Class:
    package
        [Bindable]
        public class Person
            public var firstName:String;
            public var lastName:String;
            public var phone:String;
    and do this in the Manager:
    public function setPerson():void {
         var person = new Person();
         person.firstName = "Steve";
         person.lastName = "Smith";
         person.phone = "555.555.1212";
    OR just have this declaired in the Manager as
    [Bindable] public var person:ObjectProxy;
    public function setPerson():void {
         person = new ObjectProxy();
         person.firstName = "Steve";
         person.lastName = "Smith";
         person.phone = "555.555.1212";
    Thanks to anyone who wants to help me become a better developer!

    ObjectProxy access is significantly slower that data class access.  ObjectProxy will not tell you if you mistype the name of a property and you can spend hours trying to find some place were you typed ssm insead of ssn.

  • Calling a function in another class that is not the App delegate nor a sngl

    Hi all-
    OK- I have searched and read and searched, however I cannot figure out an easy way to call a function in another class if that class is not the app delegate (I have that down) nor a singleton (done that also- but too much code)
    If you use the method Rick posted:
    MainView *myMainView = [[MainView alloc] init];
    [MyMainView goTell];
    That works, however myMainView is a second instance of the class MainView- I want to talk to the instance/Class already instantiated.
    Is there a way to do that without making the class a singleton?
    Thanks!

    I had some trouble wrapping my head around this stuff at first too.
    I've gotten pretty good at letting my objects communicate with one another, however I don't think my method is the most efficient or organized way but I'll try to explain the basic idea.
    When you want a class to be able to talk to another class that's initialized elsewhere, the class your making should just have a pointer in it to the class you want to communicate with. Then at some point (during your init function for example) you should set the pointer to the class you're trying to message.
    for example in the app-delegate assume you have an instance of a MainView class
    and the app-delegate also makes an instance of a class called WorkClass
    If you want WorkClass to know about MainView just give it a pointer of MainView and set it when it's instantiated.
    So WorkClass might be defined something like this
    //WorkClass.h
    @import "MainView.h"
    @interface WorkClass : NSObject
    MainView *myPointerToTheMainView;
    @property (retain) myPointerToTheMainView;
    -(void)tellMainViewHello;
    @end
    //WorkClass.m
    @import "WorkClass.h"
    @implementation WorkClass
    @synthesize myPointerToTheMainView;//this makes getter and setter functions for
    //the pointer and allows us to use the dot
    //syntax to refrence it.
    -(void)tellMainViewHello
    [myPointerToTheMainView hello]; //sends a message to the main view
    //assume the class MainView has defined a
    //method -(void)hello
    @end
    now somewhere in the app delegate you would make the WorkClass instance and pass it a reference to the MainView class so that WorkClass would be able to call it's say hello method, and have the method go where you want (to the single instance of MainView owned by the app-delegate)
    ex:
    //somewhere in app-delegate's initialization
    //assume MainView *theMainView exists and is instantiated.
    WorkClass *myWorkClass = [[WorkClass alloc] init];
    myWorkClass.myPointerToTheMainView = theMainView; //now myWorkClass can speak with
    // the main view through it's
    // reference to it
    I hope that gets the basic idea across.
    I'm pretty new to Obj-c myself so if I made any mistakes or if anyone has a better way to go about this please feel free to add
    Message was edited by: kodafox

  • Calling a function inside another class

    I have the following two classes and can't seem to figure to figure out how to call a function in the top one from the bottom one. The top one get instantiated on the root timeline. The bottom one gets instantiated from the top one. How do I call functions between the classes. Also, what if I had another call instantiated in top one and wanted to call a function in the bottom class from the second class?
    Thanks a lot for any help!!!
    package
         import flash.display.MovieClip;
         public class ThumbGridMain extends MovieClip
              private var grid:CreateGrid;
              public function ThumbGridMain():void
                   grid = new CreateGrid();
              public function testFunc():void
                   trace("testFunc was called");
    package
         import flash.display.MovieClip;
         public class CreateGrid extends MovieClip
              public function CreateGrid():void
                   parent.testFunc();

    kglad,
    Although I agree that utilizing events the way you attempted in your suggestion is better for at least a reason of eliminating dependency on parent, still you code doesn't not accomplish what Brian needs.
    Merely adding event listener to grid instance does nothing - there is no mechanism in the code that invokes callTGMFunction - thus event will not be dispatched. So, either callTGMFunction should be called on the instance (why use events - not direct call - in this case?), or grid instance needs to dispatch this event based on some internal logic ofCreateGrid AFTER it is instantiated - perhaps when it is either added to stage or added to display list via Event.ADDED. Without such a mechanism, how is it a superior correct way OOP?
    Also, in your code in ThumbGridMain class testFunc is missing parameter that it expects - Event.
    Am I missing something?
    I guess the code may be (it still looks more cumbersome and less elegant than direct function call):
    package
         import flash.display.MovieClip;
         import flash.events.Event;
         public class ThumbGridMain extends MovieClip
             private var grid:CreateGrid;
             public function ThumbGridMain():void
                 grid = new CreateGrid();
                 grid.addEventListener("callTGMFunction", testFunc);
                 addChild(grid);
            // to call a CreateGrid function named cgFunction()
             public function callCG(){
                 grid.cgFunction();
             public function testFunc(e:Event):void
                 trace("testFunc was called");
    package
         import flash.display.MovieClip;
         import flash.events.Event;
         import flash.events.Event;
         public class CreateGrid extends MovieClip
             public function CreateGrid():void
                 if (stage) init();
                 else addEventListener(Event.ADDED, callTGMFunction);
             // to call a TGM function
             public function callTGMFunction(e:Event = null):void
               // I forgot this one
                removeEventListener(Event.ADDED, callTGMFunction);
                this.dispatchEvent(new Event("callTGMFunction"));
            public function cgFunction(){
                 trace("cg function called");
    I think this is a case of personal preference.
    With that said, it is definitely better if instance doesn't rely on the object it is instnatiated by - so, in this case, either parent should listen to event or call a function directly.

  • Cannot call member function on object type

    On 8.1.6 I cannot call a member function from SQL in the way described in the manual.
    The following example is almost copied from the manual:
    create or replace TYPE foo AS OBJECT (a1 NUMBER,
    MEMBER FUNCTION getbar RETURN NUMBER);
    create or replace type body foo is
    MEMBER FUNCTION getbar RETURN NUMBER is
    begin
    return 45;
    end;
    end;
    CREATE TABLE footab(col foo);
    SELECT col,foo.getbar(col) FROM footab; -- OK
    select col,col.getbar() from footab; -- ERROR
    The second select is the way it should be, but I get an error "invalid column name".
    Using the first select, I get the result. This is strange because this is more or less the 'static member' notation (filling in the implicit self parameter myself).
    Is this a known bug in 8.1.6, maybe fixed in later versions?

    Konstantin,
    Did you use loadjava to load the compiled class into the Oracle Database?
    Regards,
    Geoff
    Hello!
    I need to write a member function for object type with java.
    for example:
    create type test as object(
    id number,
    name varchar2(20),
    member function hallo return number);
    create type body test as
    member function hallo return number
    as language java
    name 'test.hallo() return int;
    create table test of test;
    My java-file is:
    public class test {
    public int hallo() {
    return 5;
    select t.hallo() from test t;
    It's does not run. Why?
    I get always an error back. Wrong types or numbers of parameters!!
    please help me.
    thanks in advance
    Konstantin

  • How to redefine GOS toolbar function "SEND OBJECT WITH NOTE" for deliveries

    Hello Abapers,
    for inbound and outbound deliveries (tcodes VL01N, VL02N, VL03N, VL31N, VL32N, VL33N) I have to replace the GOS toolbar function SEND OBJECT WITH NOTE with a redefined function matching the following specifications:
    - Title field needs a different content
    - Text (note content) should be filled by default, maybe with standard text, but can be overwritten
    - All attachments in the attachment list of the object should be included by default or be selectable thru an additional button
    Also possible could be an addiitonal toolbar function SEND ATTACHMENTS WITH NOTE as a copy of SEND OBJECT WITH NOTE.
    Although I checked the SDN forums for a matching solution, I couldn't find one in tons of GOS threads.
    Perhaps someone had solved a similar problem to send obejct with notes from GOS toolbar with several of the object's attachments.
    Maybe some GOS classes have to be redefined for that, but this should only be available for deliveries, not for the other BOR types.
    I'm waiting for your ideas.
    Best regards,
    Klaus
    Edited by: Klaus Babl on Feb 16, 2012 10:13 AM

    No the list of steps done to solve the issue:
    1. Copy of class CL_GOS_SRV_SEND_OBJECT to new class /SIE/IS_BSD_GOS_SRV_SEND_ATT.
    2. SM30 for table SGOSATTR: New entry for new service ZSO_SENDATT for the new class.
    3. Copy of methods ON_SERVICE_SUCCEEDED, CHECK_STATUS, CREATE_ROOT_ITEM and ON_LINK_CREATED from class CL_GOS_SRV_ATTACHMENT_LIST to the new class.
    4. New code added to the top of method CHECK_STATUS to show the service for deliveries only:
    IF  is_lporb-typeid  NE  'BUS2015'
    AND is_lporb-typeid  NE  'LIKP'.  
        ep_status = mp_status_invisible.
        EXIT.
    ENDIF.
    5. Copy of function group SAPLSGOS_OUTBOX and function module SGOS_SEND_OBJECT_WITH_NOTE to own copies.
    6. Before calling cl_bcs=>short_message  there are several steps to do:
    - CALL METHOD cl_binary_relation=>read_links
    - CALL FUNCTION 'SO_DOCUMENT_READ_API1' for all links
    - cl_document_bcs=>create_document for all those documents (we are using types ATTA, NOTE and URL)
    - APPEND those created documents to the attachment table and pass it to i_attachments of cl_bcs=>short_message
    Solved issue!
    COMMENT: This SDN wiki document is outdated and doesn't work any more:
    http://wiki.sdn.sap.com/wiki/display/Snippets/ABAP-SendingGOSattachmentstoanemailaddress
    Best regards,
    Klaus

  • How to add new object class to a material ?

    Hi experts,
    I have to add new object class to a material ( classification class ) and then add new characteristics values for the material ....But i do not know which FM to do this , If you please to give me the solution for this problem
    PS: rewards immediately
    Thanks,

    Hi,
    Check this  CALL FUNCTION 'CLVM_CLASS_BOOK' Run it for IN UPDATE TASK
    Reward if useful,

Maybe you are looking for

  • Short-sighted approach to Bluetooth and Wi-fi.

    I've just bought an Ipad - which I think is a truly amazing bit of kit. However within 36 hours I've discovered some very basic shortcomings in the software design in respect to both Bluetooth and Wi-fi. I was so shocked at their absence that I ran t

  • CALL_TRANSACTION in Background

    Hi. We want to execute CALL_TRANSACTION SP12 in background job. And we did Migration from 46B to ERP2005. Before Migration we could do it normaly, but now we can't do it. In addition, we can do it on foreground, but we can't do it in background,----

  • Display disaster!

    Hi all, I have a major problem with LR though I'm guessing it's not LR's fault. I have two Samsung monitors and if I drag LR from one to the other, after about a second, the image changes significanty in terms of color rendition. On the right monitor

  • Values in Colum as separate columns

    I have a table that looks like this: Company (varchar), FieldName (varchar) Valuex (varchar) Data may look like this: Company Fieldname Valuex 123 Name John 123 MiddleName C 123 LastName Smith I would like to write a query that comes out like this: C

  • Access Connections 5 and up issues

    Hi, For years our organization has been using Access Connections 4.52 flawlessly.  Recently we purchased a boat load of R500 notebooks.  At this point, we were forced to upgrade to version 5.20 as 4.52 will not recognize the wireless card. With 4.52,