HashMap and reference

Hi,
In HashMap or any other collection framework in general,
when I look up something, in order for that something to be
in the collection, I need to look it up by an object with the
same reference, not an object that is "equal" by "equals()" method.
Let me give an example.
==========================
class test {
public static void main(String args[]) {
HashMap<MyObject, String> someMap =
new HashMap<MyObject, String>();
MyObject abc = new MyObject();
abc.a = 7;
someMap.put(abc, new String("roses"));
if (someMap.get(abc) != null) {
System.out.println((String) someMap.get(abc));
MyObject def = new MyObject();
def.a = 7;
if (someMap.get(def) != null) {
System.out.println((String) someMap.get(def));
class MyObject {
int a;
===================================
If the above example, the first println will print "roses",
because I have put <abc, "roses"> in the HashMap.
However, if I look up "roses" by def, which is an identical
copy of abc (but, difference reference), the HashMap
someMap will not be able to look it up and find "roses".
This is not desired in my situation.
And I notice that if "MyObject" is replaced by an immutable
class such as String or Integer, the program works as
I inteded, that is the second println also prints "roses".
How could I make the lookup in the collection (HashMap,
LinkedList, .... ) work with recognizing "equals()" (or any
mechanism to tell that two different objects are identical
copy of each other) and lookup succeeds if the key is
identical (not the same reference)?
If I could work around this problem, by simply make
"MyObject" class be something similar to those immutable
class such as String or Integer, how do I do that?
for example, could I use some kind of keyword to specify
that "MyObject" is an immutable object and thus, lookup
succeeds if two different MyObject are identical copies of each other?
Thank you very much for your help!
My question ends here.
But, just to clarify things more,
let me give 2 more examples.
This example is similar to the 1st example,
but since I use Integer instead of "MyObject",
the 2nd println in the program also prints "roses".
==========================
class test {
public static void main(String args[]) {
HashMap<Integer, String> someMap =
new HashMap<Integer, String>();
Integer abc = new Integer(7);
someMap.put(abc, new String("roses"));
if (someMap.get(abc) != null) {
System.out.println((String) someMap.get(abc));
Integer def = new Integer(7);
if (someMap.get(def) != null) {
System.out.println((String) someMap.get(def));
===================================
My third example shows why I kind of need the functionality
that I want (look up by recognizing identical copy, not just
the reference).
==========================
class test {
public static void main(String args[]) {
HashMap<MyIdentity, String> phonebook =
new HashMap<MyIdentity, String>();
MyIdentity abc = new MyIdentity();
abc.name = "heloise";
abc.age = "16";
someMap.put(abc, new String("342-5259"));
if (someMap.get(abc) != null) {
System.out.println((String) someMap.get(abc));
MyIdentity def = new MyIdentity();
def.name = "heloise";
def.age = "16";
if (someMap.get(def) != null) {
System.out.println((String) someMap.get(def));
// for the sake of argument, let's just say that
// a person is uniquely defined by name and age,
// by not by name alone.
class MyIdentity {
String name;
int age;
===================================
Since I want to look up the phonebook, possibly in
different process or different context from where I
made input to the phone book,
I won't be able to keep the reference, but I should be
able to make the identical MyIdentity object and want
to look up.
But it fails in the example.

Thank you!
I actually tried implementing equals().
But, it seems I failed to implement the correct interface of equals()
previously.
I tried something like
public boolean equals(MyObject a) {
Now that i changed it to
public boolean equals(Object a) {
it just works!
Big thanks!

Similar Messages

  • What  is difference between user group and reference user group?

    hi
    guys,
            what  is difference between user group and reference user group? 
    your regards
      p.suresh

    Hi ,
    Chk the link below for your clarifiacation.
    http://help.sap.com/erp2005_ehp_03/helpdata/EN/5c/c1c81c445f11d189f00000e81ddfac/frameset.htm
    Hope it helps.
    Regards,
    Amit
    Edited by: Amit Kotwani on Sep 2, 2008 2:15 PM

  • Difference Between HashMap and HashTable

    Difference Between HashMap and HashTable
    Please explain with an example

    I have a situation in Java Collection and i am not
    able to figure a good solution. I am scared about the
    performance and memory that wil be used
    I have 5 List objects with thousands and thousands of
    records in it. The List is populated by a database
    query using jdbcTemplate which return like 200,000
    records
    Each record is identified by POLICY_ID. They may be
    List with multiple records for a POLICY_ID
    I want to extract each POLICY_ID from all the 5 List
    and make a single List object for each POLICY_ID and
    for each List and pass it to a print job which will
    print the data for a POLICY_ID
    Example
    Let say we have POLICY_ID = 15432
    List1 has one record for 15432
    List2 has one record for 15432
    List3 has one record for 15432
    List4 has three record for 15432
    List5 has three record for 15432
    From the 200,000 records in List1 i want to generate
    a seperate list with 1 record for policy id 15432 and
    let name is Listperpolicy
    after this logic we have
    Listperpolicy1
    Listperpolicy2
    Listperpolicy3
    Listperpolicy4
    Listperpolicy5
    call print job ( Listperpolicy1, Listperpolicy2,
    Listperpolicy3, Listperpolicy4, Listperpolicy5)
    Please let me know
    Thanks a Lotttttttttdon't worry about performance until you've got a working application. second-guessing what the performance bottlenecks will be is futile

  • Hashmap and array list problems

    This is an assignment I have to do and I do NOT expect anyone to do the coding for me. I am just looking for some direction as I have no clue where to go from here. Any guidance would be very welcomed.
    We were given code that used just an Array lisThis is an assignment I have to do and I do NOT expect anyone to do the coding for me. I am just looking for some direction as I have no clue where to go next. Any guidance would be very welcomed.
    We were given code and told to "Modify the MailServer so that it uses a HashMap to store MailItems. The keys to the HashMap should be the names of the recipients, and each value should be an ArrayList containing all the MailItems stored for that recipient. " Originally it was just an ArrayList named messages. There is also a MailClient and MailItem class.
    I think I can post the messages using the HashMap now, but can't test it. I get a compiler error saying else without if even though I have an if statement. Even if I can compile, I need to make sure I am on the right track with the getNextMailItem method. It is the one I am stuck on and if I can get it to work, I can probably modify the other methods.
    I would really appreciate feedback on that one method.
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    public class MailServer
         // Storage for the arbitrary number of messages to be stored
         // on the server.
         private HashMap messages;
         private ArrayList list;
         private MailItem item;
          * Construct a mail server.
         public MailServer()
             messages = new HashMap();
             list = new ArrayList();
          * Return the next message for who. Return null if there
          * are none.
          * @param who The user requesting their next message.
         public MailItem getNextMailItem(String who)
              Iterator it = list.iterator();
              while(it.hasNext())
                MailItem item = (MailItem)it.next();
                if(messages.containsKey(who));
                    return item;
               else
                   return null;
          * Add the given message to the message list.
          * @param item The mail item to be stored on the server.
         public void post(String name, MailItem item)
             if(messages.containsKey(name))
                    list = (ArrayList) messages.get(name);
                    else {
                        list = new ArrayList();
                        list.add(item);
                        messages.put(name, list);
    }[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    The way I understand this is that MailItems are stored in per user ArrayLists, and that the ArrayLists are stored in the HashMap, and use the username as a key,
    HashMap messages = new HashMap();
    //ArrayList userMailItems = new ArrayList(); this should not be declared here, only the messages mapso given a User name, you need to get the list of mail items for that user out of the hashMap, and then return the next MailItem from the list. So given that, you don't even need to Iterate over the list:
    public MailItem getNextMailItem(String who)
    ArrayList list = (ArrayList)messages.get(who);
    if(list == null || list.size() == 0)
    return null;
    //now we get the next item from the list, we can call remove, since it returns the object we are removing.
    MailItem item = (MailItem)list.remove(0);
    return item;
    }

  • How to get subject text and Reference Object both Screens at the Header lev

    Dear Experts ,
                    I am getting only Notification Header Screen ( Subject Text, Notification system and User Status) at the Header of Notification and different Tabs under that screen.
                    I want Subject Text and Reference Object screens at header Level so that any screen Tab selected at a time I can see the Subject and Reference Object of the Notification.
                    Pls tell me is there any way so I can Include 2 screens( Subject and Reference Object at the Header Level.)
    With best regards,
    Narendra

    Narendra,
    You can't in the standard system.
    Only the tabs are configurable.
    PeteA

  • Standard and Reference Purchasing Org

    What is the difference between standard and Reference purchasing organization?
    In which scenario  it is used?
    Regards,
    Komal

    Dear Komal,
    Please find difference of both these term & its application in simple manner.
    A) Reference Purchase Organization( Also called as Central Pur Org.)
    1)Used to map cross purchasing organization procurement transaction
    2) Possible to use other purchasing organization to use conditions of this Purchase Organization
    3) Allow to access contract
    4) In customizing you can configure which data ( i.e. contract or conditions ) a purchasing organization can access
    5) a multilevel reference relationship is not possible
    6) Purchasing Info record for central Purchasing organization must exist.
    7) This is normally at client level.
    B) Standard Purchase Organization:
    1) If a plant is having more than one purchasing organization , one of the purchasing organization  is designated as standard Purchase Organization.
    2)It is used for Transaction of pipeline material , Consignment material or stock transfer orders.
    3) In source determination system automatically pulls this Purchase Organization
    4) For goods issue Purchasing Info record of standard Purchase Organization is used.
    5) Standard Purchase Organization info record is used for auto PO generation during GR
    I thinks this will clear your concept.
    If useful reward points,
    Vivek Maitra

  • My master pages have disappeared from the View menu in Frame Maker and I can't get to them. View does show body pages and reference pages.

    Master pages went missing from my FrameMaker 12 setup about 4 days ago. I can see body and references pages. I have tried reinstalling. The master pages are missing from all of my FrameMaker documents, absolutely all of them. I have done two new installations of FM 12, no fix.

    Does the old shortcut still work? [Esc, v, M plus its close kin Esc, v, R for Reference pages and Esc, v, B for Body pages – all case-sensitive]
    Also, does "missing" mean you select View master pages and get a blank screen? while double-checking the view shortcuts, I discovered this can be replicated by turning off borders [Esc, v, b] in Master page view … if you happen to be using a Master page layout with no header or footer. But I have also, occasionally, ended up with blank master pages even when they should have had content. It's a mystery.

  • Check double invoice with GL account and Reference field

    Dear SAP GURU's,
    I am very new to SDN. I have one query.
    I know we have the option of control double invoice against Vendor/Customer by using reference field. But here my client is asking that control has to be from GL account and reference field, becoz some times he will receive the shipping bills 3 or 4 times agianst one billing document ( i am booking Transporter Vendor invoice by using FB60) with same bill number but expense GL's will be different most of the times. Some times knowingly or unknowingly same GL Expenditure account will be repeated with the same shipping bill number. This was happend most of the times.
    So can i know how can i get the GL account and Reference field checking and error message for the same.
    Thanks & Regards,
    Shobha.

    Dear Shobha,
    I feel that having a check on GL is not a good idea.  If your client insists you can go for an exit or BTE. 
    We used BTE to have the same functionality of Logistics for FI documents also in our office.
    Duplicate Invoice check process documentation is given below for your ready reference --
    with Regards
    Check Flag for Double Invoices or Credit Memos
    Indicator which means that incoming invoices and credit memos are checked for double entries at the time of entry.
    Use
    Checking Logistics documents
    Firstly, the system checks whether the invoice documents have already been entered in the Logistics invoice verification; the system checks invoices that are incorrect, or invoices that were entered for invoice verification in the background.
    Checking FI documents
    The system then checks whether there are FI or Accounting documents that were created with the original invoice verification or the Logistics verification, and where the relevant criteria are the same.
    Checking Logistics documents
    In checking for duplicate invoices, the system compares the following characteristics by default:
    Vendor
    Currency
    Company code
    Gross amount of the invoice
    Reference document number
    Invoice document date
    If all of these characteristics are the same, the system issues a message that you can customize.
    When you enter credit memos or subsequent adjustments, the system does not check for duplicate invoices.
    Exception: Country-specific solution for Argentina, where invoices and credit memos are checked for duplicate documents.
    No message is issued if you enter a document that has previously been reversed.
    Dependencies
    The system only checks for duplicate invoices in Materials Management if you enter the reference document number upon entering the invoice.
    In Customizing for the Logistics invoice verification, you can specify that the following characteristics should not be checked:
    Reference document number
    Invoice document date
    Company code
    This means that you can increase the likelihood that the system will find a duplicate invoice, because you can reduce the number of characteristics checked.
    Example
    The following document has already been entered and posted:
    Reference document number: 333
    Invoice date: 04/28/00
    Gross invoice amount: 100.00
    Currency: EUR
    Vendor: Spencer
    Company code: Munich
    You have made the following settings in Customizing:
    The field "Reference document number" and "Company code" are deselected, which means that these characteristics will not be checked.
    Now you enter the following document:
    Reference document number: 334
    Invoice date: 04/28/00
    Gross invoice amount: 100.00
    Currency: EUR
    Vendor: Spencer
    Company code: Berlin
    Result
    Because you entered a reference document when you entered the invoice, the system checks for duplicate invoices.
    The reference document number and the company code are different from the invoice entered earlier, but these characteristics are not checked due to the settings you have made in Customizing.
    All other characteristics are the same. As a result, the system issues a message that a duplicate entry has been made.
    If the "Reference document number" had been selected in Customizing, the system would have checked the document and discovered that it was different from the invoice entered earlier, so it would not have issued a message.
    Checking FI documents
    Depending on the entry in the field "Reference", one of the following checks is carried out:
    1. If a reference number was specified in the sequential invoice/credit memo, the system checks whether an invoice/credit memo has been posted where all the following attributes agree:
    Company code
    Vendor
    Currency
    Document date
    Reference number
    2. If no reference number was specified in the sequential invoice/credit memo, the system checks whether an invoice/credit memo has been posted where all the following attributes agree:
    Company code
    Vendor
    Currency
    Document date
    Amount in document currency

  • RERAPP and reference field

    Hi,
    does anyone know how SAP determines the Reference field (XBLNR) when generating vendor open items via Periodic posting run RERAPP?
    Is there any possibility to define a certain reference by the user?
    Thanks,
    Sonja

    Hi,
    The reference table and reference field are the fields which specify the currency key or Unit of Measure. Suppose if the user specifies a currency amount say 1000$, the currency amount field would indicate the amount 1000 and the currency key indicates that the currency specified is in Dollars.
    A reference field is needed for all currency and quantity fields as the figures in this field need a currency or unit. If you have no reference field and table for fields of this kind you will get a syntax error. This syntactic constraint reflects a semantic fact: A figure in a field does not tell you a lot if you do not know to which quantities or currencies the figure is related: It does not suffice to know that you have, for example, five items, but you need to know if you have five meters, five Euros, five pound etc. And this information is provided the reference field and table.
    Reference: http://www.sap-abap4.com/abap/qa-sap-abap-dictionary-23/
    <REMOVED BY MODERATOR>
    regards,
    Ramya
    Edited by: Alvaro Tejada Galindo on Apr 14, 2008 4:58 PM

  • User Defined Fields and Reference Fields on the B/S

    Dear Experts,
       On the balance sheet in SAP 9.0/8.82 once you click on the expanded button, there are user defined fields and reference fields which are blank. Could someone assist on how to use them ?
    Kind Regards

    Hi Martin,
    If you add any user defined fields (UDF) in Journal Entry (JE) screen, You can use the udf's in the
    balance sheet report.
    Regards
    Neslin

  • 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.

  • Stopping individual services and references in composites

    Hi All,
    We know that we can shutdown and start up composites.Is there any way by which we people can start or stop the individual services and references in the composite.Like if there is file and db adapter in a composite and i want to stop just the file adapter.Can this be achieved in 11g.
    Thanks!!!!

    Thanks Anuj,
    But that will stop the services and references for all the composites but we want for a particular composite.
    Regards

  • Routing number of operations and reference operation  in the order

    Hi experts,
    If anyone knows about Routing number of operations and reference operation  in Maintenance order , please explain.
    is it used for maintenance order? if yes, please mention the path from which I can see or note the number generated by the system as Routing number of operations or operation task list no. or reference operation
    Regards,

    Hello,
    Routing number of operations in the order"(field-->AUFPL) of the order at table AFKO, using order number. Find the Operation counter number of the operation at table AFVC using "Routing number of operations in the order".
    From above we can fetch the Operation Level data of Order by using the Routing number of operations in the order"(field>AUFPL)  .Routing number of operations in the order>which solely identity of the Operation for your order after creation of order it is created this number.
    Regards,
    Rakesh
    Edited by: RAKESH ASHOK MANE on Sep 23, 2010 2:47 PM

  • LSMW for Routing and Reference Operations

    Hello Experts,
    I am working on data transfer for Routing and Reference Operations (TCode CA01 and CA11).
    I found one LSMW for Routing provided by SAP but didnt found for Reference Operations. Does anyone has more stuff related to Data transfer for Routing and Reference Operation.
    Please share with me. My email id is [email protected]
    Thanks in Advance..
    Harkamal

    Hi Harkamal,
        Check the programs:
    RCPTRA01
    RCPTRA02
    Go to SE38 .
    GIve the name of the program.
    Choose the Documentation radio-button.
    Click Display.
    It is pretty well documented.
    Regards,
    Ravi Kanth Talagana

  • How to use start and reference trigger on HI-Scope digitizer

    HI,
    I would like to ask about the start and reference trigger with PCI-5124.
    I found an sample VI on the following link, however it doesn't work as I expected.
    http://zone.ni.com/devzone/cda/epd/p/id/2998
    The VI "start_and_reference_trigger.vi" can detect both start and reference trigger in my system and they start data acquisition.
    It starts data acquisition when both start and reference triggers are input.
    However what I would like to do is:
     1. Sampling rate at 200MHz with record length 1500 with one channel.
     2. Receive the start trigger (i.e. 50Hz)
     3. Receive the reference trigger (i.e. 50kHz)
     4. For every reference trigger, I would like to acquire the data, i.e. acquiring 1500 data for each 100 reference trigger (not with the combination with the start trigger)
    Start trigger: _|^|_________________________________________
    Ref   trigger:______|__|__|__|__|__|__|__|__|__|__|__|__|__|__|____
                                       ^    ^    ^    ^   ^   ^   ^   ^    ^    ^   ^    ^    ^   ^  
                                     trigger timings that I would like to acquire
    With the sample VI "start_and...", I found that it acquires when both start and reference trigger comes and the data acquisition is only after the one reference trigger. 
    I hope my explanation is understandable and I can have a solution soon.
    解決済!
    解決策の投稿を見る。

    Hi Tom 1225,
    Thanks for posting on Discussion Forum.  Based on your statement, I guess, what you want PCI-5124 to do is what general bench-top type oscilloscopes do.  To realize that functionality, at the end of each sampling of a record length, PCI-5124 has to rearm its trigger for its next sampling.  The amount of "rearm time" is listed in "trigger" section on 5124 manual, said that the rearm time is 10[us] when TDC is ON and 2[us] when TDC is OFF.  So, we have to keep in mind that, if one waveform of measured signal is shorter than 2[us] (TDC OFF), more than one waveform may fail to kick the trigger, because 5124 still rearming its trigger.     
    I made two samples and attached them on this post.  
    In "Sample SW Timing Trigger.vi", trigger rearm occurs at software timing, when the time NI-Scope Start function is called.  In "Sample HW Timing Trigger.vi", trigger rearm occurs at hardware timing.  As seen on the block diagram, for a hardware timing trigger rearm, the number in "number of records" of horizontal setting function should be equal to the times of the trigger-based measurements.  If you have any question on my sample VIs, feel free to ask.  If my post resolves your problem, please click on the green "解決策に決定" icon on my post.  
    Osamu Fujioka
    Applications Enginner 
    National Instruments Japan
    添付:
    Sample SW Timing Trigger Rearm.vi ‏28 KB
    Sample HW Timing Trigger Rearm.vi ‏31 KB

Maybe you are looking for