Equals in Hashtable

I have a Hashtable which maps int[] to an array of objects called cell.
Declared like this Hastable<int[], cell[]> tableMy problem is this. The hashtable uses Object.equals - but I want to use Arrays.equals. For instance:
int[] keyLookup = new int[] {0,1,2,3};
if(table.containsKey(keyLookup)){
}However this doesn't work because:
int[] one = new int[] {0,1,2,3};
int[] two = new int[] {0,1,2,3};one.equals(two) is false;
I want the behaviour of Arrays.equals(one, two) is true.
Is it possible to achieve this? Because I don't want to have to enumerate over all the keys performing Array.equals!

This has not entirely solved my problem.
I now have what I've called a Signature, which models the int[] and have overridden the equals method to use the Arrays.equals method. e.g.:
int[] one = new int[] {0,1,2,3};
int[] two = new int[] {0,1,2,3};
System.out.println("Object equals = " + one.equals(two));
System.out.println("Arrays equals = " + Arrays.equals(one, two));
Signature sOne = new Signature(one);
Signature sTwo = new Signature(two);
System.out.println("Signature equals = " + sOne.equals(sTwo));Which is great and now gives me the desired behaviour, here's the output
Object equals = false
Arrays.equals = true
Signature equals = true
But the problem is I have not overridden the hashCode method; and so two objects which are now equal return different hashCodes - resulting in Hashtable.get/containsKey being incorrect.
I could write an implementation of this based on the values in the integer array of the Signaure but I am wary of doing this because it could be easy to make a mistake.
Any suggestions on either how to safely override hashCode or an alternative approach?

Similar Messages

  • Hashtable equalent data type in PLSQL

    Hi,
    From java i am calling stored procedure, i want to pass hashtable to it.Data in hashtable consists of key and value. Key is some integer and value is an Object[](array)
    So i want to know datatype equal to Hashtable in PLSQL.
    Can anyone help out in solving about problem.
    --Kalyan

    Look Associative Arrays (Index-By Tables) :
    create or replace package Kalyan
    IS
    type t1 is record (empno number, ename varchar2(200), hiredate date,....);
    type t2 is table of t1 index by binary_integer;
    procedure f1(par1 in out t2);
    end;

  • Help needed in understanding the code.

    Hi All,
    I am just trying to understand the Java code in one Self Serice page. However, I am having tough in understanding the CO code. In the prosessRequest class, I have the below code.
    oapagecontext.putTransactionValue("AddAssignmentInsertRowFlag", "N");
    oaapplicationmodule.getTransaction().commit();
    As soon as, oaapplicationmodule.getTransaction().commit();
    gets executed, its calling some other class. Not sure what is being called, but i can see the log messages that its executing some other class which actually does the calls to DB APIs and inserting data into main tables.
    Can you please explain me what is being called to make DB API calls. I would greatly appreciate your help.
    Thanks in Advance!
    - Rani
    ****************************Here is the full code of class for your reference****************************
    public void processFormRequest(OAPageContext oapagecontext, OAWebBean oawebbean)
    if("SelectedResourceLink".equals(oapagecontext.getParameter("event")))
    Debug.log(oapagecontext, this, "SelectedResourceLink has been pressed", 3);
    oapagecontext.redirectImmediately("OA.jsp?akRegionCode=PA_SELECTED_RESOURCES_LAYOUT&akRegionApplicationId=275", true, "RP");
    String s = (String)oapagecontext.getTransactionValue("AssignmentType");
    super.processFormRequest(oapagecontext, oawebbean);
    Debug.log(oapagecontext, this, "in processFormRequest()", 3);
    OAApplicationModule oaapplicationmodule = oapagecontext.getRootApplicationModule();
    if(!"Y".equals(oapagecontext.getParameter("paMass")))
    String s1 = oapagecontext.getParameter("event");
    if("lovUpdate".equals(s1))
    Debug.log(oapagecontext, this, "*** User Selected a value from LOV ***", 3);
    String s3 = oapagecontext.getParameter("source");
    Debug.log(oapagecontext, this, "*** lovInputSourceId = " + s3 + " ***", 3);
    if("ProjectNumber".equals(s3) && "Project".equals(s))
    Hashtable hashtable = oapagecontext.getLovResultsFromSession(s3);
    String s10 = (String)hashtable.get("ProjectId");
    Debug.log(oapagecontext, this, "*** ProjectId ***" + s10, 3);
    oapagecontext.putTransactionValue("paProjectId", s10);
    if("Project".equals(s))
    Debug.log(oapagecontext, this, "*** Setting default value for Delivery assignment ***", 3);
    oaapplicationmodule.invokeMethod("defaultProjectAttrs");
    if("RoleName".equals(s3))
    Hashtable hashtable1 = oapagecontext.getLovResultsFromSession(s3);
    Debug.log(oapagecontext, this, "*** RoleName Hashtable Contents ***" + hashtable1.toString(), 3);
    String s11 = (String)hashtable1.get("RoleId");
    Debug.log(oapagecontext, this, "*** RoleId ***" + s11, 3);
    Debug.log(oapagecontext, this, "*** AssignmentType = " + s + "***", 3);
    if("Open".equals(s))
    Debug.log(oapagecontext, this, "*** Calling defaultJobAttrs for Open Assignment***", 3);
    Serializable aserializable[] = {
    s11
    oaapplicationmodule.invokeMethod("defaultJobAttrs", aserializable);
    if("Template".equals(s) || "Open".equals(s))
    Debug.log(oapagecontext, this, "*** Defaulting Competencies ***" + s11, 3);
    OAViewObject oaviewobject = (OAViewObject)oapagecontext.getApplicationModule(oawebbean).findViewObject("RoleCompetenciesVO");
    oaviewobject.setMaxFetchSize(-1);
    oaviewobject.setWhereClauseParam(0, s11);
    oaviewobject.executeQuery();
    Debug.log(oapagecontext, this, "*** End LOV event ***", 3);
    String s4 = "";
    String s8 = "";
    OASubTabLayoutBean oasubtablayoutbean1 = (OASubTabLayoutBean)oawebbean.findIndexedChildRecursive("AddAssignmentSubTabLayout");
    if("Project".equals(s) && !oasubtablayoutbean1.isSubTabClicked(oapagecontext))
    OAViewObject oaviewobject1 = (OAViewObject)oapagecontext.getApplicationModule(oawebbean).findViewObject("AddNewAssignmentVO");
    s4 = (String)oaviewobject1.first().getAttribute("ProjectId");
    s8 = (String)oaviewobject1.first().getAttribute("ProjectNumber");
    Debug.log(oapagecontext, this, "*** lProjectId = " + s4, 3);
    Debug.log(oapagecontext, this, "*** lProjectNumber = " + s8, 3);
    if("Project".equals(s) && !oasubtablayoutbean1.isSubTabClicked(oapagecontext) && !StringUtils.isNullOrEmpty(s8))
    Debug.log(oapagecontext, this, "Delivery Assignment, Project Number is there but no Project Id", 3);
    if(s4 == null || s4.equals(""))
    ViewObject viewobject = oapagecontext.getApplicationModule(oawebbean).findViewObject("ObtainProjectId");
    if(viewobject == null)
    String s14 = "SELECT project_id FROM PA_PROJECTS_ALL WHERE segment1 =:1";
    viewobject = oaapplicationmodule.createViewObjectFromQueryStmt("ObtainProjectId", s14);
    viewobject.setWhereClauseParam(0, s8);
    viewobject.executeQuery();
    int j = viewobject.getRowCount();
    if(j != 1)
    Debug.log(oapagecontext, this, "Error : Project Number is Invalid or not unique", 3);
    OAException oaexception4 = null;
    oaexception4 = new OAException("PA", "PA_PROJECT_NUMBER_INVALID");
    oaexception4.setApplicationModule(oaapplicationmodule);
    throw oaexception4;
    oracle.jbo.Row row = viewobject.last();
    if(row != null)
    Object obj2 = row.getAttribute(0);
    if(obj2 != null)
    s4 = obj2.toString();
    if(s4 != null)
    oapagecontext.putTransactionValue("paProjectId", s4);
    if(oaapplicationmodule.findViewObject("AddNewAssignmentsVO") != null)
    oaapplicationmodule.findViewObject("AddNewAssignmentVO").first().setAttribute("ProjectId", s4);
    } else
    Debug.log(oapagecontext, this, "Error : No rows returned in Project Number query", 3);
    OAException oaexception5 = null;
    oaexception5 = new OAException("PA", "PA_PROJECT_NUMBER_INVALID");
    oaexception5.setApplicationModule(oaapplicationmodule);
    throw oaexception5;
    String s12 = "F";
    if(s4 != null && !s4.equals(""))
    String s13 = Security.checkUserPrivilege("PA_ASN_CR_AND_DL", "PA_PROJECTS", s4, oapagecontext, false);
    if("F".equals(s13))
    OAException oaexception3 = null;
    oaexception3 = new OAException("PA", "PA_ADD_DELIVERY_ASMT_SECURITY");
    oaexception3.setApplicationModule(oaapplicationmodule);
    Debug.log(oapagecontext, this, "ERROR:" + oaexception3.getMessage(), 3);
    throw oaexception3;
    OAViewObject oaviewobject2 = (OAViewObject)oapagecontext.getApplicationModule(oawebbean).findViewObject("AddNewAssignmentVO");
    Object obj = oaviewobject2.first().getAttribute("BillRateOverride");
    Object obj1 = oaviewobject2.first().getAttribute("BillRateCurrOverride");
    Object obj3 = oaviewobject2.first().getAttribute("MarkupPercentOverride");
    Object obj4 = oaviewobject2.first().getAttribute("DiscountPercentOverride");
    Object obj5 = oaviewobject2.first().getAttribute("TpRateOverride");
    Object obj6 = oaviewobject2.first().getAttribute("TpCurrencyOverride");
    Object obj7 = oaviewobject2.first().getAttribute("TpCalcBaseCodeOverride");
    Object obj8 = oaviewobject2.first().getAttribute("TpPercentAppliedOverride");
    Object obj9 = null;
    Object obj10 = null;
    Debug.log(oapagecontext, this, "in AddAssignmentsTopCO processFcstInfoRg(): getting the implementation options", 3);
    Object obj11 = oaviewobject2.first().getAttribute("BrRateDiscReasonCode");
    Object obj12 = oapagecontext.getTransactionValue("rateDiscReasonFlag");
    Object obj13 = oapagecontext.getTransactionValue("brOverrideFlag");
    Object obj14 = oapagecontext.getTransactionValue("brDiscountOverrideFlag");
    String s22 = oapagecontext.getParameter("BillRateRadioGroup");
    if("BRCurrencyRadioButton".equals(s22))
    Debug.log(oapagecontext, this, "BRCurrencyRadioButton chosen", 3);
    if(obj == null || obj1 == null)
    Debug.log(oapagecontext, this, "error", 3);
    OAException oaexception6 = new OAException("PA", "PA_CURR_BILL_RATE_REQUIRED");
    oaexception6.setApplicationModule(oaapplicationmodule);
    throw oaexception6;
    } else
    if("BRMarkupRadioButton".equals(s22))
    Debug.log(oapagecontext, this, "BRMarkup%RadioButton chosen", 3);
    if(obj3 == null)
    Debug.log(oapagecontext, this, "error", 3);
    OAException oaexception7 = new OAException("PA", "PA_MARKUP_PERCENT_REQUIRED");
    oaexception7.setApplicationModule(oaapplicationmodule);
    throw oaexception7;
    } else
    if("BRDiscountRadioButton".equals(s22))
    Debug.log(oapagecontext, this, "BRDiscount%RadioButton chosen", 3);
    if(obj4 == null)
    Debug.log(oapagecontext, this, "error", 3);
    OAException oaexception8 = new OAException(oapagecontext.getMessage("PA", "PA_DISCOUNT_PERCENT_REQUIRED", null));
    oaexception8.setApplicationModule(oaapplicationmodule);
    throw oaexception8;
    if("Y".equals(oapagecontext.getTransactionValue("paMass")) || "Admin".equals(s) || "Template".equals(s))
    Debug.log(oapagecontext, this, "Need not have this check for team templates ", 3);
    } else
    if(obj13 != null && obj13.equals("Y") && obj12 != null && obj12.equals("Y") && "BRCurrencyRadioButton".equals(s22) && StringUtils.isNullOrEmpty((String)obj11))
    Debug.log(oapagecontext, this, "error 1", 3);
    OAException oaexception9 = new OAException("PA", "PA_RATE_DISC_REASON_REQUIRED");
    oaexception9.setApplicationModule(oaapplicationmodule);
    throw oaexception9;
    if(obj14 != null && obj14.equals("Y") && obj12 != null && obj12.equals("Y") && "BRDiscountRadioButton".equals(s22) && StringUtils.isNullOrEmpty((String)obj11))
    Debug.log(oapagecontext, this, "error 2", 3);
    OAException oaexception10 = new OAException("PA", "PA_RATE_DISC_REASON_REQUIRED");
    oaexception10.setApplicationModule(oaapplicationmodule);
    throw oaexception10;
    Debug.log(oapagecontext, this, "*** Selected transfer price radio shr = " + s22, 3);
    oapagecontext.putTransactionValue("BROGroupSelected", s22);
    Debug.log(oapagecontext, this, "*** 1 :Selected bill rate radio = " + s22, 3);
    if(s22 != null)
    oapagecontext.putSessionValue("BROGroupSelected", s22);
    s22 = oapagecontext.getParameter("TransferPriceRadioGroup");
    Debug.log(oapagecontext, this, "*** Selected transfer price radio = " + s22, 3);
    if("TPCurrencyRadioButton".equals(s22))
    Debug.log(oapagecontext, this, "***TPCurrencyRadioButton chosen", 3);
    if(obj5 == null || obj6 == null)
    Debug.log(oapagecontext, this, "error", 3);
    OAException oaexception11 = new OAException("PA", "PA_CURR_RATE_REQUIRED");
    oaexception11.setApplicationModule(oaapplicationmodule);
    throw oaexception11;
    } else
    if("TPBasisRadioButton".equals(s22))
    Debug.log(oapagecontext, this, "***TPBasisRadioButton chosen", 3);
    if(obj7 == null || obj8 == null)
    Debug.log(oapagecontext, this, "error", 3);
    OAException oaexception12 = new OAException("PA", "PA_BASIS_APPLY_PERCENT_REQD");
    oaexception12.setApplicationModule(oaapplicationmodule);
    throw oaexception12;
    oapagecontext.putTransactionValue("TPORadioGroupSelected", s22);
    if(oaapplicationmodule.findViewObject("AddNewAssignmentVO").first().getAttribute("RoleId") != null)
    Debug.log(oapagecontext, this, "*** Role Id is + " + oaapplicationmodule.findViewObject("AddNewAssignmentVO").first().getAttribute("RoleId"), 3);
    if(oapagecontext.getParameter("SearchCompetencies") != null)
    String s2 = "OA.jsp?akRegionCode=PA_COMP_SEARCH_LAYOUT&akRegionApplicationId=275&paCallingPage=AddAssignment";
    oapagecontext.redirectImmediately(s2, true, "RP");
    OASubTabLayoutBean oasubtablayoutbean = (OASubTabLayoutBean)oawebbean.findIndexedChildRecursive("AddAssignmentSubTabLayout");
    if(s.equals("Project") && oasubtablayoutbean.isSubTabClicked(oapagecontext) && !StringUtils.isNullOrEmpty((String)oapagecontext.getTransactionValue("paProjectId")))
    String s5 = "PA_ASN_FCST_INFO_ED";
    String s9 = "F";
    s9 = Security.checkUserPrivilege(s5, "PA_PROJECTS", (String)oapagecontext.getTransactionValue("paProjectId"), oapagecontext, false);
    if(s9.equals("F"))
    Debug.log(oapagecontext, this, "Error : PA_ASN_FCST_INFO_ED previelge not found", 3);
    OAException oaexception2 = null;
    oaexception2 = new OAException("PA", "PA_NO_SEC_FIN_INFO");
    oaexception2.setApplicationModule(oaapplicationmodule);
    throw oaexception2;
    if(oapagecontext.getParameter("GoBtn") != null)
    if("Y".equals(oapagecontext.getTransactionValue("paMass")) && "0".equals(oapagecontext.getTransactionValue("paNumSelectedResources")))
    OAException oaexception = new OAException("PA", "PA_NO_RESOURCE_SELECTED");
    oaexception.setApplicationModule(oapagecontext.getRootApplicationModule());
    Debug.log(oapagecontext, this, "ERROR:" + oaexception.getMessage(), 3);
    throw oaexception;
    String s6 = "T";
    if(s.equals("Admin") && "Y".equals(oapagecontext.getTransactionValue("paMass")) && "1".equals(oapagecontext.getTransactionValue("paNumSelectedResources")))
    Debug.log(oapagecontext, this, "resource id[19] is " + (String)oapagecontext.getTransactionValue("paResourceId"), 3);
    if(oapagecontext.getTransactionValue("AdminSecurityChecked") == null)
    String s7 = Security.checkPrivilegeOnResource("-999", (String)oapagecontext.getTransactionValue("paResourceId"), SessionUtils.getResourceName((String)oapagecontext.getTransactionValue("paResourceId"), oapagecontext), "PA_ADM_ASN_CR_AND_DL", null, oapagecontext, false);
    if("F".equals(s7))
    OAException oaexception1 = new OAException("PA", "PA_ADD_ADMIN_ASMT_SECURITY");
    oaexception1.setApplicationModule(oapagecontext.getRootApplicationModule());
    Debug.log(oapagecontext, this, "ERROR:" + oaexception1.getMessage(), 3);
    throw oaexception1;
    if("SUBMIT_APPRVL".equals(oapagecontext.getParameter("AddAsgmtApplyAction")))
    oapagecontext.putTransactionValue("Save", "N");
    else
    oapagecontext.putTransactionValue("Save", "Y");
    String as[] = oaapplicationmodule.getApplicationModuleNames();
    String as1[] = oaapplicationmodule.getViewObjectNames();
    Debug.log(oapagecontext, this, "no of app module: " + as.length, 3);
    Debug.log(oapagecontext, this, "no of view: " + as1.length, 3);
    for(int i = 0; i < as.length; i++)
    Debug.log(oapagecontext, this, "app module: " + as, 3);
    for(int k = 0; k < as1.length; k++)
    Debug.log(oapagecontext, this, "app module: " + as1[k], 3);
    Debug.log(oapagecontext, this, "*** assignmentType = " + s, 3);
    Debug.log(oapagecontext, this, "*** projectId = " + oapagecontext.getTransactionValue("paProjectId"), 3);
    if("Project".equals(s) && !StringUtils.isNullOrEmpty((String)oapagecontext.getTransactionValue("paProjectId")) && !"Y".equals(oapagecontext.getParameter("paMass")))
    Debug.log(oapagecontext, this, "*** Setting default staffing owner for add delivery assignment -- projectId = " + oapagecontext.getTransactionValue("paProjectId"), 3);
    oaapplicationmodule.invokeMethod("setDefaultStaffingOwner");
    OAViewObject oaviewobject3 = (OAViewObject)oaapplicationmodule.findViewObject("RoleCompetenciesVO");
    oaviewobject3.setMaxFetchSize(0);
    oaviewobject3.setRangeSize(-1);
    oracle.jbo.Row arow[] = oaviewobject3.getAllRowsInRange();
    for(int l = 0; l < arow.length; l++)
    RoleCompetenciesVORowImpl rolecompetenciesvorowimpl = (RoleCompetenciesVORowImpl)oaviewobject3.getRowAtRangeIndex(l);
    Debug.log(oapagecontext, this, "roleCompetenciesVORowImpl" + rolecompetenciesvorowimpl, 3);
    rolecompetenciesvorowimpl.setPlsqlState((byte)0);
    oapagecontext.putTransactionValue("AddAssignmentInsertRowFlag", "N");
    oaapplicationmodule.getTransaction().commit();
    if("Y".equals(oapagecontext.getTransactionValue("paMass")) && !"1".equals(oapagecontext.getTransactionValue("paNumSelectedResources")))
    if(!"SUBMIT_APPRVL".equals(oapagecontext.getParameter("AddAsgmtApplyAction")))
    Debug.log(oapagecontext, this, "Save, Mass, NumSelectedResources>1", 3);
    Debug.log(oapagecontext, this, "work flow has been launched", 3);
    OADialogPage oadialogpage = new OADialogPage((byte)3, new OAException("PA", "PA_MASS_ASSIGNMENT_CONFIRM"), null, "OA.jsp?akRegionCode=PA_RESOURCE_LIST_LAYOUT&akRegionApplicationId=275&addBreadCrumb=N", null);
    oadialogpage.setRetainAMValue(false);
    oapagecontext.redirectToDialogPage(oadialogpage);
    return;
    Debug.log(oapagecontext, this, "SaveAndSubmit, Mass, NumSelectedResources>1", 3);
    putParametersOnSession(oapagecontext);
    int i1 = 0;
    int j1 = 0;
    String s21 = "SelectedResourceId";
    int l1 = Integer.parseInt(oapagecontext.getTransactionValue("paNumSelectedResources").toString());
    Debug.log(oapagecontext, this, "size of resourceArray = " + l1, 3);
    String as2[] = new String[l1];
    for(; !"END".equals(oapagecontext.getTransactionValue(s21.concat(Integer.toString(i1)))); i1++)
    if(oapagecontext.getTransactionValue(s21.concat(Integer.toString(i1))) != null)
    Debug.log(oapagecontext, this, "resource id = " + oapagecontext.getTransactionValue(s21.concat(Integer.toString(i1))).toString(), 3);
    as2[j1] = oapagecontext.getTransactionValue(s21.concat(Integer.toString(i1))).toString();
    j1++;
    SessionUtils.putMultipleParameters("paResourceId", as2, oapagecontext);
    Debug.log(oapagecontext, this, "redirect to Mass Submit for Approval page", 3);
    oapagecontext.redirectImmediately("OA.jsp?akRegionCode=PA_MASS_SUBMIT_LAYOUT&akRegionApplicationId=275&paCallingPage=MassAdd&paProjectId=" + oapagecontext.getTransactionValue("p_project_id"), false, "RP");
    return;
    if("RETURN_TO".equals(oapagecontext.getParameter("AddAsgmtApplyAction")))
    Debug.log(oapagecontext, this, "Return to Option Selected ", 3);
    String s15 = (String)oapagecontext.getTransactionValue("PrevPageUrl");
    int k1 = s15.indexOf("OA.jsp?");
    s15 = s15.substring(k1);
    Debug.write(oapagecontext, this, "*** RETURN_TO URL: " + s15, 3);
    oapagecontext.redirectImmediately(s15);
    } else
    if("ADD_ANOTHER".equals(oapagecontext.getParameter("AddAsgmtApplyAction")))
    Debug.log(oapagecontext, this, "Add Another Option Selected", 3);
    oaapplicationmodule.invokeMethod("resetAddNewAssignment");
    if(oaapplicationmodule.findViewObject("RoleCompetenciesVO") != null)
    oaapplicationmodule.findViewObject("RoleCompetenciesVO").clearCache();
    String s16;
    if(!s.equals("Project") && !s.equals("Admin"))
    s16 = "OA.jsp?akRegionCode=PA_ADD_ASSIGNMENTS_PAGE_LAYOUT&akRegionApplicationId=275&paProjectId=" + oapagecontext.getTransactionValue("paProjectId") + "&paAssignmentType=" + s + "&OA_SubTabIdx=0";
    else
    s16 = "OA.jsp?akRegionCode=PA_ADD_ASSIGNMENTS_PAGE_LAYOUT&akRegionApplicationId=275&paResourceId=" + oapagecontext.getTransactionValue("paResourceId") + "&paAssignmentType=" + s + "&OA_SubTabIdx=0";
    Debug.log(oapagecontext, this, "nextUrl " + s16, 3);
    if("Template".equals(s))
    oapagecontext.redirectImmediately(s16, true, "S");
    else
    oapagecontext.redirectImmediately(s16, false, "S");
    } else
    if("UPDATE_DETAILS".equals(oapagecontext.getParameter("AddAsgmtApplyAction")))
    Debug.log(oapagecontext, this, "Update Details Selected ", 3);
    String s17 = "";
    if("Staffed".equals(s))
    s17 = "ProjStaffedAsmt";
    else
    if("Admin".equals(s))
    s17 = "AdminAsmt";
    else
    if("Project".equals(s))
    s17 = "PersonStaffedAsmt";
    else
    if("Open".equals(s))
    s17 = "OpenAsmt";
    else
    if("Template".equals(s))
    s17 = "TemplateAsmt";
    String s19 = "OA.jsp?akRegionCode=PA_ASMT_LAYOUT&akRegionApplicationId=275&paProjectId=" + oapagecontext.getTransactionValue("paProjectId") + "&paAssignmentId=" + oapagecontext.getTransactionValue("wfOutAssignmentId") + "&paCalledPage=" + s17 + "&addBreadCrumb=RP";
    Debug.log(oapagecontext, this, "UPDATE_DETAILS: URL: " + s19, 3);
    oapagecontext.redirectImmediately(s19, false, "RP");
    if(s.equals("Staffed") || s.equals("Admin") || s.equals("Project"))
    String s18 = (String)oapagecontext.getTransactionValue("wfOutResourceId");
    String s20 = (String)oapagecontext.getTransactionValue("wfOutAssignmentId");
    Debug.log(oapagecontext, this, "outResourceId " + s18, 3);
    Debug.log(oapagecontext, this, "outAssignmentId " + s20, 3);
    if("SUBMIT_APPRVL".equals(oapagecontext.getParameter("AddAsgmtApplyAction")))
    if(s.equals("Staffed"))
    oapagecontext.redirectImmediately("OA.jsp?akRegionCode=PA_SUBMIT_ASMT_APR_LAYOUT&akRegionApplicationId=275&paAsgmtId=" + s20 + "&paResourceId=" + s18 + "&paProjectId=" + oapagecontext.getTransactionValue("paProjectId") + "&paAsgmtAprStatus=ASGMT_APPRVL_WORKING&paAssignmentType=" + s + "&paCallingPage=AddAssignment", false, "RP");
    return;
    oapagecontext.redirectImmediately("OA.jsp?akRegionCode=PA_SUBMIT_ASMT_APR_LAYOUT&akRegionApplicationId=275&paAsgmtId=" + s20 + "&paResourceId=" + s18 + "&paAsgmtAprStatus=ASGMT_APPRVL_WORKING&paAssignmentType=" + s + "&paCallingPage=AddAssignment", false, "RP");

    Hi Rani,
    As soon as the transaction is commited the methods in the VORowImpl Class are called.
    You can check in the VORowImpl class and search for the log messages.
    Thanks,
    Gaurav

  • Two equal objects, but different classes?

    When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
    The source codes of the program bind_ref.java are listed as below:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.naming.*;
    import javax.naming.spi.ObjectFactory;
    import java.util.Hashtable;
    public class bind_ref {
    public static void main( String[] args ) {
    // Set up environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
    env.put( Context.PROVIDER_URL, "file:/daniel/" );
    Context ctx = null;
    File f = null;
    Fruit fruit1 = null, fruit2 = null;
    byte [] b = new byte[10];
    try {
    ctx = new InitialContext( env );
    Hashtable the_env = ctx.getEnvironment();
    Object [] keys = the_env.keySet().toArray();
    int key_sz = keys.length;
    fruit1 = new Fruit( "Orange" );
         SubReference ref1 = fruit1.getReference();
    ctx.rebind( "reference", fruit1 );
         fruit2 = ( Fruit )ctx.lookup( "reference" );
         System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
         System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
         System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
         System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
         System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
         System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
    } catch( Exception ne ) {
    System.err.println( "Exception: " + ne.toString() );
    System.exit( -1 );
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    All the outputs are shown as below:
    =======================================================
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    FruitFactory: obj's class = (class javax.naming.Reference)
    FruitFactory: obj's hashCode = -1759114666
    FruitFactory: obj = (Reference Class Name: Fruit
    Type: fruit
    Content: Orange
    FruitFactory: ( obj instanceof SubReference ) = false
    FruitFactory: subref_class_name = (Fruit)
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    ref1's class = (class SubReference)
    fruit2.myRef's class = (class javax.naming.Reference)
    ( ref1 instanceof SubReference ) = true
    ( fruit2.myRef instanceof SubReference ) = false
    ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
    ref1.equals( fruit2.myRef ) = true
    ========================================================
    I hightlight the critical codes and outputs related to the strangeness with bold texts.
    Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?

    It can also depend on how you implement the equals method.
    class Cat {
        String name;
        Cat(String n) {
            name = n;
    class Dog {
        String name;
        Dog(String n) {
            name = n;
        public boolean equals(Object o) {
            return name.equals(o.name);
        public static void main(String[] args) {
            Dog d = new Dog("Fred");
            Cat c = new Cat("Fred");
            System.out.println(d.equals(c));
    }

  • Java/xml/hashtable-part 2

    Hi, I'm back. I had a question a few days ago using JDOM to read and write XML files with Java, and then creating a hashtable. Someone replied and helped considerably, but as a beginner programmer, I still have a few problems. My XML document is HUGE, with a huge tree and the key and values that i am trying to extract are children of different elements of the tree. Mainly, I am having problems navigating through a tree. Let's say the following is my XML file (mine is much bigger than this but similar problem), and i want the key of the hashtable to be city and the value to be zipcode.
    <?xml version="1.0" ?>
    - <person>
    - <name>
    <firstname>Joe</firstname>
    <lastname>Stevenson</lastname>
    </name>
    - <homeinfo>
    <address street="12345 Jones Lane Avenue" city="Lyndburg" state="Utah" zip="32423" />
    </homeinfo>
    <phone>345-098-2342</phone>
    <email>[email protected]</email>
    <occupation>Secretary</occupation>
    - <workinfo>
    <workname>Senior Citizen's Association</workname>
    <address street="233 Great Street" city="Baltimore" state="Maryland" zip="23421" />
    </workinfo>
    </person>
    So the output i would like to see is: {Lyndburg= 32423, Baltimore=23421}
    Any help would be wonderful! thanks so much!

    As I just wrote, next time please paste your code between code tags exactly like this:
    &#91;code&#93;
    your code
    &#91;/code&#93;
    You may read the [url http://forum.java.sun.com/faq.jsp#format]formatting help for more information.
    Thank you
    I don't know what happened, maybe you didn't copy/paste my code, or made some changes that broke the code. Here is the corrected version of the code you posted:
    import java.io.*;
    import java.util.*;
    import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.filter.*;
    public class InfoMap {
        public static void main(String[] args) throws Exception {
            new InfoMap().test();
        void test() throws Exception {
            Map map = new HashMap();
            File f = new File("person.xml");
            Document doc = new SAXBuilder().build(f);
            Iterator iterator = doc.getDescendants(new Filter() {
                public boolean matches(Object obj) {
                    if ((obj instanceof Element) && ((Element)obj).getName().equals("person"))
                        return true;
                    else
                        return false;
                } // <-- this was missing
            while (iterator.hasNext()) {
                Element person = (Element)iterator.next();
                Element homeinfo = person.getChild("homeinfo");
                Element address = homeinfo.getChild("address");
                Attribute city = address.getAttribute("city");
                Attribute zip = address.getAttribute("zip");
                map.put(city.getValue(), zip.getValue());
                Element workinfo = person.getChild("workinfo");
                address = workinfo.getChild("address");
                city = address.getAttribute("city");
                zip = address.getAttribute("zip");
                map.put(city.getValue(), zip.getValue());
            System.out.println(map);
        } // <-- this was missing
    } // <-- this was missing

  • Hashtables and Objects, ugly.

    Let's see...
    I'll give you everything, then highlight problems.
    package Analyze;
    import java.io.*;
    import java.util.*;
    public class Work {
        public static int Operate(String directory, String filename, String directory2, String filename2, String ext, int number) {
            int sum=0;
            try{
                BufferedWriter out = new BufferedWriter(new FileWriter(directory+filename));
                BufferedReader in = new BufferedReader(new FileReader(directory2+filename2+ext));
                String str;
                int b;
                int w;
                int low=10000;
                int high=0;
                int count=0;
                Hashtable table=new Hashtable();
                while ((str = in.readLine()) != null) {
                    if  ((w=str.indexOf("Total Run Time"))>0)
                    {w=str.indexOf("Total Run Time");
                     String substr=str.substring(0, w-1);
                     String change="<TH>";
                     String newString=Replace.replace(str,substr,change);
                     int z=newString.indexOf(":");
                     String substr2=newString.substring(0, z+2);
                     String change2="";
                     String finalString=Replace.replace(newString, substr2, change2);
                     int i = Integer.parseInt(finalString);
                     int q=1;
                     if (table.get(new Integer(i))==null)
                        {table.put(new Integer(i),new Integer(q));}
                     if (table.get(new Integer(i))!=null)
                        {int v=Integer.parseInt(table.put(new Integer(i),new Integer(q)));
                         v=v+q;
                         table.put(new Integer(i), new Integer(v));
                     if (i>high)
                         high=i;
                     if (i<low)
                         low=i;
                     sum+=i;
                     count++;
                BufferedWriter instances = new BufferedWriter(new FileWriter("C:\\development\\test\\test_Local\\archives\\number"+Date.whatMonth()+Date.whatDay()+Date.whatYear()+"test"+number+".txt"));
                for (int n=0; n<=high; n++)
                    { if (table.get(new Integer(n))!=null)
                      {instances.write(table.get(new Integer(n))+" threads took "+n+" seconds.");
                        instances.flush();}
                instances.close();
                String strSum=""+sum;
                String strLow=""+low;
                String strHigh=""+high;
                double average=(double)sum/count;
                String strAverage=""+average;
                String strCount=""+count;
                out.write("<HTML> <BODY>");
                out.write("<P>These are the results of the stress test conducted for: "+Date.whatMonth()+"-"+Date.whatDay()+"-"+Date.whatYear()+"<P>");
                out.write("<BR><I>Total number of users ----- </I>"+strCount+" <B>(Note: This number is number of users multiplied by number of cycles.)</B>");
                out.write("<P><B>Time to complete in seconds: </B>"+strSum);
                out.write("<BR><B>The quickest thread took</B> "+strLow+" <B>seconds.</B>");
                out.write("<BR><B>The longest thread took</B> "+strHigh+" <B>seconds.</B>");
                out.write("<BR><B>The average is </B>"+strAverage+" <B>seconds.</B>");
                out.write("<P><P>The corresponding log file is: <a href=archives/"+filename2+Date.whatMonth()+Date.whatDay()+Date.whatYear()+".txt> Located in the archives bin. </A>");
                out.write("<P><P>The list of times and their instances is located :<a href=archives/number"+Date.whatMonth()+Date.whatDay()+Date.whatYear()+"test"+number+".txt> here </A>");
                NewFile.MakeFile(directory, "testlist.html");
                BufferedWriter lister = new BufferedWriter(new FileWriter(directory+"testlist.html", true));
                String strNum=""+number;
                lister.write("<a href="+filename+">Results from: "+Date.whatMonth()+"-"+Date.whatDay()+"-"+Date.whatYear()+"(Test number: "+strNum+")</A><P>");
                lister.close();
               /* File file=new File(directory+filename2);
                int compare=1;
                if (file.exists())
                {BufferedReader text = new BufferedReader(new FileReader(file));
                 String stuff;
                 if( (stuff=text.readLine())!=null)
                     compare=Integer.parseInt(stuff);
                 text.close();
                float second=((compare/sum)-1)*100;
                int benchmark=1500;
                float third=((benchmark/sum)-1)*100;
                String strThird;
                String strSecond;
                if (second < 0)
                    strSecond="<font color=red>"+second+"% </font>";
                else strSecond=""+second+"% ";
                if (third < 0)
                    strThird="<font color=red>"+third+"% </font>";
                else strThird=""+third+"% ";
                out.write("<BR><B>Compared to yesterday, there has been a </B>"+strSecond+"<B>change</B> (Note: Positive values shows the processes being done faster. Negative values demonstrate a dropoff in performance.)");
                out.write("<BR><B>Compared to the benchmark, there has been a </B>"+strThird+"<B>change</B> (Note: Positive values shows the processes being done faster. Negative values demonstrate a dropoff in performance.)");*/
                out.write("</BODY></HTML>");
                in.close();
                out.close();
                /* BufferedWriter cout = new BufferedWriter(new FileWriter("C:\\development\\test\\test_Local\\archive"+Date.whatMonth()+Date.whatDay()+".txt"));
                cout.write(strSum);
                cout.close(); */
               File fil = new File(directory2, filename2+ext);
                if (fil.exists()==false)
                    System.out.println("File doesn't exist!");
                File archive = new File("C:\\development\\test\\test_Local\\archives\\");
                if (archive.exists()==false)
                {archive.mkdir();
               /* File other=new File("C:\\development\\test\\test_Local\\archives\\"+filename2+Date.whatMonth()+Date.whatDay()+Date.whatYear()+".txt");
                boolean success= fil.renameTo(new File(archive, other.getName()));
                if(!success)
                {System.out.println("Could not move file");*/
            catch (IOException e)
            {System.out.println(e);}
            number++;
            return number;
    }Now, I don't really understand hashtables, so this may be completely wrong. However, here's the goal:
    I'm taking in a ton of ints, ranging from 1 to infinity. I want to create a hashtable which has the integer as the key, and the number of times it has come up as its value. Now, if an integer comes up more than once, I need to increase the value, I can't just throw it out. However, the hashtable keeps telling me that if I'm getting the value from a key I select and trying to put it into a new int, I'm an idiot because the value is of type Object. Now, how are objects going in, and not ints? Is my compiler just being crazy, or is it me?
    Also, is it necessary to create new Integers everytime I use a method from the hashtable? I haven't gotten past the compiling stage, so I don't know how the execution will go...
    Please note, everything except for the hashtable works. I have a classes that handle almost everything else, so Date.whatMonth() is really a valid command ;) Everything that's commented out is because I haven't completed the feature. Don't worry about that stuff.

    Okay, let's start with the return type.
    Hashtable.get(key) returns a value of type Object, as I'm sure you've noticed. It does this because that's as much as it can guarantee about the returned data; it could be any kind of Object, depending on what you put in. Java, however, remembers what kind of Object it is and stores its type internally.
    Thus...
    Object o = new Integer(1);
    System.out.println(o.intValue());...is illegal. Object.intValue() doesn't exist, and that's what you're asking it to do. However...
    Object o = new Integer(1);
    System.out.println(o.hashCode()); // legal because Object.hashCode() exists
    System.out.println( ((Integer)o).intValue() ); // legal because the Object was constructed as an Integer
    System.out.println( ((Short)o).shortValue() ); // throws a ClassCastException because the Object was not constructed as a ShortThus, all you need to do is recast the return value of Hashtable.get(Object) to the type that you know it should be. For example,
    Integer integer = (Integer)(my_hashtable.get(key_that_maps_to_integer));...is legal.
    Now, as for creating Integers every time... well, you probably shouldn't. I would recommend creating the following class to use as the value and the key. Note, however, that any object you create that is used as the key in a Hashtable should probably override the equals(Object) and hashCode() methods of Object.
    public class MutableInteger
        protected int m_value;
        public MutableInteger(int base)
            m_value = base;
        public int getValue()
            return m_value;
        public void setValue(int new_value)
            m_value = new_value;
        public int hashCode()
            // This must be done or all of the keys will map to the same hash code.  That would reduce the performance of the Hashtable to a linked list!
            return m_value;
        public boolean equals(Object o)
            // This must be done because, without it, no two MutableIntegers will be considered the same.
            if (o instanceof MutableInteger)
                // If the other MutableInteger has the same internal value, consider it legal.
                return (  ((MutableInteger)o).getValue() == m_value );  // Note the use of casting here.  instanceof has guaranteed that this cast is legal.
            } else
                // If the Object isn't a MutableInteger, it can't be equal to this one.
                return false;
    }Now, your code would read...
    MutableInteger key_object = new MutableInteger(0);   // Use as the key
    MutableInteger value_object = null;
    Hashtable table=new Hashtable();
    while ((str = in.readLine()) != null) {
        if ((w=str.indexOf("Total Run Time"))>0) {
            w=str.indexOf("Total Run Time");
            String substr=str.substring(0, w-1);
            String change="<TH>";
            String newString=Replace.replace(str,substr,change);
            int z=newString.indexOf(":");
            String substr2=newString.substring(0, z+2);
            String change2="";
            String finalString=Replace.replace(newString, substr2, change2);
            int i = Integer.parseInt(finalString);
            int q=1;
    /*new*/ key_object.setValue(i);
    /*dif*/ if (table.get(key_object)==null) {
    /*dif*/     table.put(key_object,new MutableInteger(q))  // Created as a MutableInteger.  The Hashtable won't remember, but the JVM will.
    /*new*/     key_object = new MutableInteger(0);  // Because the old one now belongs to the table.
    /*dif*/ if (table.get(key_object)!=null) {  // Won't this always be true?  You just put a value in there.
            // Am I correct in understanding that this code is designed to increase the value stored in the table by "q"?  If so, use the following code.
    /*new*/     value_object = (MutableInteger)(table.get(key_object));  // Note the cast.  We know that the Object returned was constructed as a MutableInteger; after all, we put it there.
    /*new*/     value_object.setValue(value_object.getValue()+1);
    /*new*/     table.put(key_object,value_object);
            if (i>high) high=i;
            if (i<low) low=i;
            sum+=i;
            count++;
    }Good luck, and have fun! ;)

  • Hashtable vs Vector

    Hi there,
    I was just wondering if a Hashtable is more efficient than a Vector for holding small amounts of objects.
    The fuctionality that I require allows me to use either but Id like to use the most efficient if I can find out which that would be.
    Thanks,
    Nick

    Fiontan,
    You can't compare two things that are not comparable.My bad, the Comparable interface is a Java 2 construct also. You could still code your own binary search for the Vector however, using the knowledge that it only contains Strings, which you can manually compare.
    Or, if speed really isn't important, then you could use the existing contains (was this in 1.0?) or indexOf method to test if the string exists, and just go with the linear performance. In a list with 5 elements (Each equally likely), that's less than 3 comparisons on average, compared with more than 1 (hash + equals, at minimum) for a hashtable.
    The hashtable is a special structure used to keep
    objects that are unique and accessible through a
    unique hashcode, so the access can be make in O(1).A hashtable is an implementation of both the (mathematical) map and (mathematical) set construct. A map is a function that literally maps a value from one set onto another value from another (or the same) set. If a map simply maps a value onto itself, then that map is just an identity map on a set.
    This differs from a Vector, which is simply an ordered list of values. Such a list can be a backing for larger mathematical constructs (Indeed, a similar ordered list forms part of the backing for a hashtable). Since their purpose overlaps, there may well be cases where either is appropriate. In many such cases, there will be one which is 'obviously' more appropriate, but that's no reason to assume that in all cases it is either 'one or the other'.
    But, if you don't have any key on your objects, and
    you want to add the same object several times, and you
    want to have an sequential ordered access : use a
    Vector (or a similar structure) but not an HashTable.I'd change each of your 'and's to 'or's, since a hashtable will not fulfil any of those requirements - so any one of them will render a hashtable unusable. Note that in a set, an object forms its own key.
    Just to throw a spanner in the works, I suddenly recall that in Java 1.0, String's hashCode method was rather inefficient - it creates a poor hash, and it doesn't store the result of the calculation (Meaning it is recalculated for each call to hashCode). If your strings are large, the Vector may match or out-perform the HashTable!
    -Troy

  • SAP Help Tutorial - Create a Hashtable ??

    I'm new so this will be simple - I think
    I'm attempting to follow the tutorial on SAP HELP located at:
    http://help.sap.com/saphelp_nw04/helpdata/en/44/47b87e9d780597e10000000a155369/frameset.htm
    I got threw tutorial 1 with no problem...
    When I get to the "Writing Code" section of Tutorial II, writing the mySiteMap.java code, I assume I'm suppose to use the code as written in the tutorial... however my IDE (NWDS) gives me :
    Syntax error on token "Hashtable", "interface", "class" expected
    on this block of code, (which I copied from the tutorial):
    *CODE*
    public Hashtable getEnvironment(IPortalComponentRequest request ) {
         Hashtable environment = new Hashtable();
         IUserContext userContext = request.getUser();
         if (userContext != null) {
           environment.put("NavigationPrincipal", userContext);
           String user = userContext.getUniqueName();
           if (user != null && !user.equals("")) {
              environment.put("User", user);
         return environment;
    *END CODE*
    Any help is greatly appreciated

    Put the "code" into a class and make sure there is an import statement for Hashtable.
    For instance,
    package myPackage;
    import java.util.Hashtable;
    public class MyClass
    public Hashtable getEnvironment(IPortalComponentRequest request ) {
    Hashtable environment = new Hashtable();
    IUserContext userContext = request.getUser();
    if (userContext != null) {
    environment.put("NavigationPrincipal", userContext);
    String user = userContext.getUniqueName();
    if (user != null && !user.equals("")) {
    environment.put("User", user);
    return environment;

  • Connection object as a key in a hashtable

    Hi,
    I am debugging some code where a Connection object is used as a key in a hashtable. Is this ok? Will the equals() and hashCode method be defined properly for a Connection object?
    Appreciate your help.
    Thanks!

    I am debugging some code where a Connection object is
    used as a key in a hashtable. Is this ok? Will the
    equals() and hashCode method be defined properly for a
    Connection object?First, answer the following question for yourself: how do you defined equality of Connections?
    If a class merely inherits the equals() implementation from Object, then equality is the same as referential identity. If that is Ok for you [which is the case in surprisingly many cases], there is no harm is using Connections as hashtable keys.
    Vlad.

  • How to use Hashtable in Rules Engine. And objects within objects in rules

    This is something to do with the JBoss Rules Engine.
    I have an object called 'Employee' containing variables name(string), age(int), sex(string), an object Skill and other fields not relevant.
    Now the Skill object contains name and desc as variables.
    And now i have another seperate object called Test containing two hashtable: inputHT and outputHT.
    i have appropriate data in each of the objects and the hashtable:
    Employee e = new Employee();
    e.setName("Name");
    e.setAge(18);
    e.setSex("f");
    e.getSkill().setSkill("Trainer");
    Hashtable ht = new Hashtable();
    ht.put("age", new Integer(e.getAge());
    ht.put("sex", e.getSex());
    Test t = new Test();
    t.setInputHT(ht);
    Since this is something to do with drools rules: I have the appropriate code even for that.
    Like obtaining the rules defined(.drl files) in a stream, constructing the package builder, rulebase and the working memory.
    I will now explain u my .drl files(ie the rules that i have defined) and the error that i am encountering
    when I have the rule as the following there is no error:
    rule "testRule1"
    when
    e:Employee(age >= 18, sex == "f")
    then
    System.out.println("The lady can marry");
    end
    In the above rule we can see that only two simple variables contained in the employee object is being accessed and there is no error encountered.
    But when I try to access the object "skill" in the employee object, the rule throws me an error when i am constructing the packageBuilder:
    rule "testRule2"
    when
    e:Employee(skill.name == "Trainer")
    then
    System.out.println("The skill is trainer");
    end
    The error thrown is : unexpected token 'skill' and many other dump errors and also error: expected token ')'
    I tried changing the when clause as the following:
    when
    e:Employee(skill.getName() == "Trainer")
    and also
    when
    e:Employee(skill.getName().equals("Trainer"))
    All of them throws the same above error.
    But at the same time if i access only object without its variables, it is working fine. Like:
    rule "testRule2"
    when
    e:Employee(skill == "Trainer")
    then
    System.out.println("The skill is trainer");
    end
    The above rule works properly and does not throw any error. But it is not a valid rule. But syntactically it is correct. and does not throw any error during packageBuilder.
    Similarly, the problem is with the Hashtable
    The below code works fine, but rulewise it is not valid, but syntactically correct. and does not throw any error
    rule "testHT1"
    when
    t:Test(inputHT == "f")
    then
    System.out.println("Print this");
    end
    But the following code throws error, telling unexpected token 'inputHT' :
    rule "testHT1"
    when
    t:Test(inputHT.get("sex") == "f")
    then
    System.out.println("Lady");
    end
    I even changed the when clause, but did not get the appropriate result and it threw me error.
    when
    t:Test(((String)input.get("sex")) == "f")
    and also many other variants but of no use.
    It would be of great help if u or anyone else could reply to this with some solution
    Thank you in advance

    http://forum.java.sun.com/thread.jspa?threadID=774018

  • Multiple values for one key in hashtable k, v

    So, I know that java.util.hashtable (as of Java 1.5) uses separate chaining to handle collisions. What I want to know is how to get a certain value somewhere in that bucket if they all share a common key? Javadoc says I have to search it sequentially but doesn't say how.

    OK, there's a lot of confusion on here for such a short thread :-)
    Firstly, HashMaps pick which "bucket" to store your object in based on the hash value of your object (see Object.hashCode()). However, the actual object equality test (applied to the keys during a search) is based on Object.equals(). Therefore which bucket your object is in is irrelevant - the bucketting concept is just used as a way of quickly locating a subset of all the keys in the map which might match your search value. There could very well be just a single bucket in a map and it wouldn't change its logical behaviour.
    This statement: "any Map including Hashtable, can only have a single (key,value) pair" is poorly worded. What it should say is that for any given key, a map can only hold a single value.
    Really, you don't need to think about the internal structure of maps (i.e. buckets, etc.).
    If you want to store multiple values for any given key, then make your value a list (java.util.List) and store your multiple real values inside that list.

  • How hashtable handle hash collision?

    From Class Hashtable javadoc
    "in the case of a "hash collision", a single bucket stores multiple entries,
    which must be searched sequentially."
    if a single bucket stores mulitple entries of String object, how
    could mulitple entries be retreived like this situation?
    String s = hasht.get(key)
    I tried a small test myself using two identical hascode "BB" and "Aa" and they get stored in 2 different bucket in hashtable but not mulitple entries as stated at the
    javadoc. Thank you.

    debugger indicatedumm, the hashes are the same so ur right there, you must have read the debugger wrong though
         Entry tab[] = table;
         int hash = key.hashCode();
         int index = (hash & 0x7FFFFFFF) % tab.length;
         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {  // right here it is same entry but its like a list inside the bucket
             if ((e.hash == hash) && e.key.equals(key)) {
              V old = e.value;
              e.value = value;
              return old;
    // rehashing stuff removed for post...
         // Creates the new entry.
         Entry<K,V> e = tab[index];
         tab[index] = new Entry<K,V>(hash, key, value, e);
         count++;

  • Using Hashtable

    Hello,
    I need to store <key, value> pairs in a hashtable so that I can retrieve it at a later point in time. However, the key is an object of my user defined class. The problem I'm facing is that I can put the <key, value> pair in Hashtable but at a later point in time, I'm not able to retrieve value for a given key and I get a null value always. Is this problem happening because in my user defined class I haven't implemented "equals" method? Or is it happening due to some other reason. I've given below the code snippet of my program.
    class C {
    int val ;
    public C(int v) {
    this.val = v ;
    class Test {
    public static void main(String args[]) {
    Hashtable t = new Hashtable() ;
    t.put(new C(10), new Integer(5)) ;
    /* And here, I get a null object, where as I should get the integer object that
    was put in the hashtable. */
    Integer i = (Integer)t.get(new C(10)) ;
    Thank you,
    Venkatesh

    Hi,
    The problem lies in your put and get.
    t.put(new C(10), new Integer(5)) ;By passing the hashtable key parameter as new C(10), i assume that the JVM is getting a memory allocation/reference.
    t.get(new C(10)) ;Same over here, you are creating another new reference (new instance) different from the put, therefore it return u a null.
    Cheers hope it help.
    ; )

  • Help need to know hashcode() and Equals method

    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........

    jverd wrote:
    euph wrote:
    jverd wrote:
    euph wrote:
    REFTY5_ wrote:
    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
    To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted.

  • QuickSort in HashTable - Urgent

    I am using jdk1.1.8. I need a program for sorting Hashtable. because there is no class Map in this version. I am using POS system. This only accepts jdk1.1.8.
    It is urgent. Can any one send the code pls
    regards,
    namanc

    Try something like:
    public class KeyValue {
      private Object key;
      private Object value;
      public KeyValue( Object key, Object value ) {
        this.key = key;
        this.value = value;
      public Object getKey() { return key; }
      public Object getValue() { return value; }
      public String toString() {
        return "[ "+key +", "+value +"]";
      /* testing */
      public static void main( String[] args ) {
        Hashtable ht = new Hashtable();
        ht.put("D","d");
        ht.put("A","a");
        ht.put("H","h");
        Vector v = new Vector();
        Enumeration enum = ht.keys();
        while (enum.hasMoreElements()) {
          Object key = enum.nextElement();
          Object val = ht.get( key );
          v.add( new KeyValue( key, val ) );
        Comparator c = new Comparator() {
          public boolean equals( Object o1, Object o2 ) {
            KeyValue k1 = (KeyValue)o1;
            KeyValue k2 = (KeyValue)o2;
            return k1.getKey().equals( k2.getKey() );
          public int compare( Object o1, Object o2 ) {
            KeyValue k1 = (KeyValue)o1;
            KeyValue k2 = (KeyValue)o2;
            String s1 = (String)k1.getKey();
            String s2 = (String)k2.getKey();
            return s1.compareTo( s2 );
        System.out.println("Before");
        printVector( v );
        QuickSort.sort( v, c );
        System.out.println("After");
        printVector( v );
      private static void printVector( Vector v ) {
        for (int i = 0; i < v.size(); i++) {
          System.out.println(v.get(i));

Maybe you are looking for

  • Safari window doen't open and crashes when it quits

    Recently when my wife opens Safari it opens but no windows show up. If I attempt to open an new window, it still does not open a window. When I quit out of safari it gives a warning message saying "Are you sure you want to quit Safari? 3 windows are

  • Airport extreme takes long time to establish stable Wifi to Internet connection

    Hi, I am using Airport Extreme together with Airport express (to extend the Wifi signal). When I connect my MBP, MBA or my PC to the Wifi network it takes (in 90% of cases roughly) quite a long time - even up to 20mins - to get stable Internet connec

  • Problem with Sharing

    Please can someone help - when I try to share an album the three options of E- Mail, Facebook and More appear at the bottom but they do not work. Thank you.

  • SSL certificate installed in Apache - determine browser's encryption

    Hi all, I have Apache Web Server and WebLogic6.1 Application Server. The two are connected by a plugin. All my web pages are installed in the Application server, ie. in WebLogic. I am using Apache Web Server just to direct the client requests to WebL

  • Restoring iPod when not recognised in Itunes

    My brand new 80gb Video iPod has just frozen. I've gone through as much as I can find on here with the exception of restoring teh iPod software as I can't get it to come up in iTunes to access that area! Is there a way I can restore it without iTunes