Confused !HashMap stores an object or reference ?
HashMap<Integer,Temp> m = new HashMap<Integer, Temp>();
Temp t1 = new Temp(1); /* pass the id in the constructor */
m.put(1, t1);
System.out.println(m.get(1).id); /* This prints out "1" */
t1.id = 100;
System.out.println(m.get(1).id); /* This prints out "100" */
t1 = null;
System.out.println(m.get(1).id); /* This prints out "100" */
Since externally modifying the id value of an object of temp class, which has already been inserted in the map, updates the id value of the object stored in the map, I thought that HashMap actually stores a reference and not the entire object. However if I assign a null pointer to t1 externally , still the object in HashMap is not null which means that hashMap has its own copy ??
Or does java play a smart trick and check whether a non-null object reference is being modified, and if it is, then all of its copies in any of the collections would be updated ?
Or I am missing something really simple ?
Remember that t1 is also a reference to the same object as the map. When changing the object through t1's reference the accessing the object through the map will show this change as you specify.
But, when you set the t1 to reference null (point at nothing) it does not mean the actual object is deleted, lost or changed. It still exists, but now only referenced by the map.
Consider this:
Integer a = new Integer(1); // a points to the Integer object
Integer b = a; // b points to this same object. (not pointing to a, but the same object as a)
System.out.println( b );
b = null; // Now b point to null, but the Integer object is still referenced by a
System.out.println( b );
System.out.println( a );- Roy
Similar Messages
-
Ho to store java objects in oracle database
HI
for me the sceanario is,
i neeed to create , dynamically a table at the time of specified action.
i need to store the values retreieved from session and store it in a database..
for example
User usr=session.getAttribute("usr"); i need to store the user object.
and hashtable and hashmap values without iterating.
please suggest at the earliest
can it be done?
Regards,
Rameshmy requirement is like that,bcos of two different weblogic servers need to acess the central database.which contains user information.
The user object from first server will be stored in database.and the second server will retrieve the user information and it will set for its application.
please suggest me how to store java objects in database.
regards,
Ramesh -
Service Object Init References
Has anyone come up with a good work around to allow Service Objects to
reference other service objects in their init methods or during application
startup. Since we can't specify the order in which Service Objects start,
is there a way we can execute some code once all Service Objects have come
online?
Will this idea work?
Start a task in the init method that loops for the referenced service object
to not be nil, then references the needed SO. For example:
while true do
if LogMgrSO = Nil then
task.delay(100);
else
exit;
end if;
end while;
Eric Rasmussen
Project Manager
Online Resources & Communications Corporation
(703)394-5128
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>Hi,
Sorry to answer so late ! I left (one year ago may be) some Tool code on
the Mailing list on that subject.
May be you have to consider some different cases :
1°) Is a Service started because it is only instanciated (<> NIL)?
2°) Forte insures that the first services to be started on a partition
are DBsession and DBResource Managers.
3°) A local Service or a distributed service are not exactly treated the
same way.
4°) The init() method has a specific way to run : the allocations are
made at the end.
1°) When a Service is not NIL it is only that it is instanciated. So
your initialization sequence is not endded may be or
the service is not insured to be started properly. It should be
important if you need to load a cache for instance. I
would recommand to test that a service is ON (for DBsessions for
instance) and to add (if possible) a state to determine
that a service is properly started.
2°) This is only available if you are inside the same partition on the
same machine. So if you have to synchronize with
external ressources from the partition you will need to treat them like
other services.
3°) A local Service will be NIL and then instanciated. The classname
will be the same as in the workshop.
A distrubuted service (exactly a service which is not on the same
partition) will have a different classname (Classname+Proxy).
So the external service proxy may be instanciated but the So May not,
and you will get a DistributedAccessException.
4°) The init() method may not be the best location for a synchronization
if you need to use an array for instance to
store you dependencies. So I would use a start task on an InitService()
method to avoid that problem.
Options :
- A dependency could be optionnal : after a certain amount of tries you
can abort synchronization on the service.
- You can use synchronization on "cold" and "hot" startup of services.
- You can develop a service agent which cold have instruments to see
dependencies and states, and commands to stop/start services.
- The Delay you may play should be different for each service you are
waiting for.
- The order of dependencies should have an importance (first put
mandatory dependancies, and then optional ones).
- A Service is not only a Service Object, but could also be just a
reference to an instance through a container for example.
- Some kind of autoStart : should I start all my services at the
beginning of my application or could I start some services
at the first call ? This should be available if you use your own
application protocole and if your services are inside some
service managers for instance.
Remarks :
Thoses concepts have been tested on a Framework from R2 to R3 of Forte
with success. With those, you can imagine
starting the application without knowing if the database is running, the
application will wait for the database
to be mounted. An other advantage of the synchronization is that you
will resolve the naming of the services at
the begining of the application. Then, you can stop the environment
manager and the application will still work
(for the clients which were already started of course). You can also
imagine transfering your partitions from one
node to an other at run-time.
Hope this helps,
Daniel Nguyen
Freelance Forte Consultant
Stephen McHenry wrote:
>
At 11:04 AM 10/1/98 -0700, John Jamison wrote:
begin
while true do
begin
..attempt "remote" SO reference..
exit; // while true do loop
exception
when e:UsageException do // if in same partition and not yet
initialized,
// you get a NIL object exception
task.errormgr.clear;
when e:DistributedAccessException do (or RemoteAccessException)
// if in a different partition, get this
error
task.errormgr.clear;
end;
event loop
aTimer : Timer = new (tickInterval=5*1000); // 5 seconds -
adjust to taste
aTimer.isActive=true;
when aTimer.Tick do
aTimer.IsActive=false;
exit;
end event;
end while;
end;One of the problems I see with all of these "catch the exception and try
again" schemes is that they fail to take into account that the SO you are
calling may, in fact, never appear (due to some sort of problem, of course)
and then you never exit this loop. It's a "liveness" problem with this
approach. So, be sure to add some alternate way out after 1 minute (or
whatever your particular threshold is) and raise an exception yourself.
Always gotta think about what happens if something goes wrong... ;-)
Stephen
|===========================================================================
===|
|Stephen McHenry | Design Consulting |Training courses
offered: |
|Advanced Software Tech | | -Distributed
Obj-Oriented |
|305 Vineyard Town Ctr #251| [email protected] | Analysis &
Design |
|Morgan Hill, CA 95037 | (408) 776-2720 x210 | -Intro to Object
Technology|
|USA | http://www.softi.com | -Advanced OO Design
|
|===========================================================================
===|
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>-
To unsubscribe, email '[email protected]' with
'unsubscribe forte-users' as the body of the message.
Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/> -
Moving object instead references
I want to copy an object into a matrix, and then equal that object to zero. But it something goes wrong, I suspect this is because only a reference is copied into the matrix, and not the object itself. And when I remove the object, the reference is obsolete. Is there a way to avoid this? I tried implenting the Cloneable interface in the object, and then putting a clone in the matrix, but it still doesn't work. Thanks
Your conception seems like C program. Be careful to do Object programmation.
In Java, remember that you have only references (equivalent to pointers in C).
In java you manipulate only the references through the variables.
An object is never set to null, only the variables which contains references to this object. The object is still here but not reachable.
Look this code :
MyObject var1 = new MyObject();
MyObject var2 = var1;
var1 = null;
Now let see how the program works :
new MyObject() create an instance of the class MyObject and store it at the adress 2000 (for example).
MyObject var1 = new MyObject();
In the created variable var1, the adress of the newly created object will be stored. var1 <-- 2000
MyObject var2 = var1;
We create a new variable var2 in which we store the value of the variable var1 i.e. : 2000 : var2 <-- 2000
var1 = null;
In the variable var1 the value is set to null : var1 <-- null.
At this moment the variable var1 contains no reference (null) and var2 still contains 2000 the adress of the object in memory.
I hope it is clearer for you,
Denis -
Passing objects by reference in PL/SQL
Hi,
I have come across an unexpected problem using object types in PL/SQL that is causing me some grief. I'm from a Java background and am relatively new to Oracle Objects but what I'm trying to do is fairly trivial, I think. The code below illustrates the problem.
--- cut here ---
CREATE OR REPLACE TYPE test_obj_t AS OBJECT
num INTEGER,
CONSTRUCTOR FUNCTION test_obj_t RETURN SELF AS RESULT
CREATE OR REPLACE TYPE BODY test_obj_t IS
CONSTRUCTOR FUNCTION test_obj_t RETURN SELF AS RESULT IS
BEGIN
num := 0;
RETURN;
END;
END;
CREATE OR REPLACE PACKAGE test_obj_ref AS
PROCEDURE init(o IN test_obj_t);
PROCEDURE inc;
FUNCTION get_num RETURN INTEGER;
END;
CREATE OR REPLACE PACKAGE BODY test_obj_ref IS
obj test_obj_t;
PROCEDURE init(o IN test_obj_t) IS
BEGIN
obj := o;
END;
PROCEDURE inc IS
BEGIN
obj.num := obj.num + 1;
END;
FUNCTION get_num RETURN INTEGER IS
BEGIN
RETURN obj.num;
END;
END;
--- cut here ---
The object type test_obj_t holds a integer and the test_obj_ref package holds a 'reference' to an instance of the object.
To test the above code I run this PL/SQL block:
declare
obj test_obj_t;
begin
obj := test_obj_t;
test_obj_ref.init(obj);
dbms_output.put_line('obj.num='||obj.num);
dbms_output.put_line('test_obj_ref.get_num='||test_obj_ref.get_num);
test_obj_ref.inc;
dbms_output.put_line('obj.num='||obj.num);
dbms_output.put_line('test_obj_ref.get_num='||test_obj_ref.get_num);
test_obj_ref.inc;
dbms_output.put_line('obj.num='||obj.num);
dbms_output.put_line('test_obj_ref.get_num='||test_obj_ref.get_num);
end;
giving the output:
obj.num=0
test_obj_ref.get_num=0
obj.num=0
test_obj_ref.get_num=1
obj.num=0
test_obj_ref.get_num=2
It appears that the object held by the test_obj_ref package is being incremented as expected, but I would have expected the object declared in the PL/SQL block to be pointing to the same object and so should report the same incremented values.
I suspect that the object is copied in the call to test_obj_ref.init() so I end up with two object instances, one that is held by the test_obj_ref package and one in the anonymous block. Although, I thought that all IN parameters in PL/SQL are passed by reference and not copied!
Am I right?
Is passing objects by reference possible in PL/SQL, if so how?
I'm using Oracle 10.2.0.3.
Cheers,
Andy.the object being passed to the test_obj_ref.init+ procedure is passed by reference; however, when you assign it to your package variable obj it is being copied to a new instance. you can pass object instances as parameters to procedures using the +IN OUT [NOCOPY]+ *calling mode, in which case modifications to the attributes of the passed object will be reflected in the calling scope's instance variable.
oracle's only other notion of an object reference is the +"REF <object-type>"+ datatype, which holds a reference to an object instance stored in an object table or constructed by an object view.
hope this helps...
gerard -
Does Java pass objects by Reference
The following is my code:
public static boolean isValid(String tester, Integer intHours, Integer intMinutes)
int dotPosition = tester.indexOf('.');
String hours = tester.substring(0, dotPosition);
String minutes = tester.substring(dotPosition +1, tester.length());
try {
intHours = Integer.valueOf(hours);
intMinutes = Integer.valueOf(minutes);
} catch (NumberFormatException nfe) {
return false;
return true;
What Iam trying to do is pass the Integer Objects by reference so that they retain their values outside of the scope of the function. My teacher told me that objects are passed by reference in Java but (even though the values are being changed within the function they are not retaining their values outside the scope of the function. Was my teacher wrong?aden_jones wrote:
So to get behaviour similar to passing by reference I would need to create my own object and give it a method e.g. MyObject.changeValue(new_value) but I can't do that with Integer objects because I can't change their actual value I can only change the Integer Object that is being pointed at??You cannot achieve behavior that duplicates PBR with Java.
However, if by "similar to passing by reference" you mean that the method makes a change that the caller can see, then, yes, you need to pass a reference to a mutable object, and change that object's state inside the method.
void foo(Bar bar) {
bar.setBaz(123);
Bar bar = new Bar();
bar.setBaz(999);
foo(bar);
// after foo() completes, the caller now sees that the Bar object's internal state has changed
// from 999 to 123Note the difference between changing the value of a caller's variable (which can be done with PBR, and cannot be done in Java) and changing the state of the single object pointed to by both the caller's variable and the method's copy of that variable (which can be accomplished in Java, as it does not rely on PBR). -
How to store java object in oracle
Hi all,
is it possible to store jva object in oracle.
I have defined myClass. It have only data fields ( no methods).
I make myClass myObject = new myClass();
How can I store this object in oracle DB.
Many thanks in advance.1.Convert this object into stream of Bytes.
2.create a new InputStream from these Byte array.
2.Use the setBinaryStream to set the values inside the table's column.
3.Store this object as a Blob in the table (column type must be Blob).
Hope this helps.
Sudha
PS:- Somebody explained in this forum how to convert an Object into Byte array . -
ORA-22806 : not an object or reference in 10gRel2
Hi,
We have recently successfully upgraded our oracle 8i database to 10.2.0.1
database is up and running fine, but
one of the user created procedure is giving error as below :
ORA-22806 : not an object or reference
See the below code :
=============
v_cnt:=0;
Check_Str := 'SELECT COUNT(*) FROM P_EMP_HOLIDAY_DATE
WHERE company_id=:p_Comp_id
AND branch_id = :rec_branch.branch_id
AND employee_id =:rec_emp.employee_id
AND :v_nxt_date IN holiday_date';
EXECUTE IMMEDIATE Check_Str INTO v_cnt USING p_Comp_id,rec_emp.branch_id, rec_emp.employee_id,v_nxt_date;
Put_Any_Line('v_cnt : ' || v_cnt);
when we run the procedure it gives the error at line 186 .i.e the line with EXECUTE IMMEDIATE statement in above
so where is the problem ?
this procedure was running fine without any problem in our oracle 8.1.7.0 version now showing error in 10.2.0.1
is there any syntax problem that is not being suported in the upgraded version i.e. 10.2.0.1
how to get it solved ?
As this is very urgent to solve so any immediate support would be appreciated.
with regardsWhat is Put_Any_Line ? Why are you using dynamic sql here ?
As this is very urgent to solve so any immediate support would be appreciated.Ok, then please, do not hesitate to use the Oracle support, and see how it can be immediate support.
Nicolas. -
Application Object Library Reference Manual in EBS 11.5.9 Docs
Hi,
I have bumped to a reference of the book "Application Object Library Reference Manual". Since this reference is about an old EBS version(10.6) and i want the equivalent of this for the EBS 11.5.9. , can you please write which one is this from url:
http://download.oracle.com/docs/cd/B12190_11/current/html/docset.html
Many thanks,
SimHi,
Actually , i have read on some docs located at :
http://www.bryanthompsononline.com/oracle/2008/05/06/download-oracle-aim-applications-implementation-methodology-software/
about the above reffered Oracle EBS document. I have searched on the typical Oracle EBS 11.5.9. doc , but i've not found this exactly doc (with this title). So , i have asked if anybody could point me to the relative doc on EBS 11.5.9. docs set......
Many thanks for the link anyway.....
Greetings,
Sim -
Rotate object by Reference Point?
I did a search on the forum on how to rotate an object by % using one of the object's reference points but came up empty.
It seems like something I've overlooked. I'm sure there's data on it, but I can't find it. Can anyone show me how to do this.
Thanksapp.layoutWindows[0].transformReferencePoint = AnchorPoint.topLeftAnchor;
myObject.rotationAngle = 30;
Peter -
How to store flash objects in different location?
How store flash objects in different location?
Is this is possible to achieve?
reply me soonHi,
I believe you meant to post your question to the Flash forums: http://forums.adobe.com/community/flashplayer
This forum deals with Flash Access, Adobe's Digital Rights Management solution.
cheers,
/Eric. -
Object casting: confusion in ABAP Objects: Complete Reference book
Hi,
During Object Assignments using casting, is a Type Test carried out during the syntax check or at runtime?
A.5.2.2 (page 1008) of 'ABAP Objects: The Complete Reference' says about Widening Cast: "...you must check at runtime...". However on the next page under A.5.3.2 it says of Widening Cast in Data References: "The syntax check precludes...".
A.5.4 (page 1010) concerns Assignments between Object Reference Variables, but makes no mention of whether checks are carried out by a syntax check or at runtime.
Also nowhere does it mention when Type Tests for Narrow casting takes place. Can anyone clear my confusion please? Unfortunatly I don't know enough about this stuff to test by writing some code.
Thanks.William,
Your questions can be answered by the following rule for object references, which I found in the book "ABAP Objects" by Horst Keller and Sascha Krüger:
"... that the static type of the target variable must be equal to or more general than the dynamic type of the source variable."
Here "static type" means the type with which an object reference variable is declared. "Dynamic type" is the type that the object reference variable has at runtime. The dynamic type of an object reference is always more special than its static type, otherwise a runtime error occurs.
With this rule all your questions can be answered:
1. The Narrowing Cast is always checked during the syntax check. Example:
DATA o_ref1 TYPE REF TO object.
DATA o_ref2 TYPE REF TO class_1.
o_ref1 = o_ref2.
Here the reference o_ref2 has a dynamic type "class_1" or a subclass of it, which is narrower than its static type "class_1", which is narrower than the static type "object" of the reference o_ref1. Therefore, the syntax check says that the assignment is OK.
2. The Widening Cast is always checked at runtime and requires an assignment using the operator ?=. If you use the operator = in the assignment, a syntax error occurs. Therefore the following example produces a syntax error (try it yourself):
DATA o_ref1 TYPE REF TO object.
DATA o_ref2 TYPE REF TO class_1.
o_ref2 = o_ref1.
The correction for this syntax error is:
DATA o_ref1 TYPE REF TO object.
DATA o_ref2 TYPE REF TO class_1.
o_ref2 ?= o_ref1.
Now the syntax check is satified, and the correctness of the widening cast is checked at runtime.
Kind regards,
Michael Kraemer
Message was edited by: Michael Kraemer -
Problem with Persistent Object as Reference Attribute of Persistent Object
Hello All,
I have a problem with a persistent class that contains a reference attribute to another persistent class. I can write the reference object attribute to the DB but when I read the reference attribute back from the DB the object is null. Allow me to explain...
I have two tables; one is a data table with one key field of type OS_GUID, the second is a mapping table with several business key fields and two further fields; an instance GUID and a class identifier GUID. The data table is used to contain all the data for an object. The mapping table is used to hold a relationship between the GUID assigned in the data table and the business key. The mapping table has been structured in this way by following the help here:
http://help.sap.com/saphelp_erp2005vp/helpdata/en/df/e785a9e87111d4b2eb0050dadfb92b/frameset.htm
and the field mapping in persistent class for the mapping table has been mapped following the help here:
http://help.sap.com/saphelp_erp2005vp/helpdata/en/06/f23c33638d11d4966d00a0c94260a5/frameset.htm
The code I use to create entries in the data and mapping table is:
<-snip->
DATA:
gv_blank_data_guid TYPE REF TO zcl_ps_data,
gv_data_guid TYPE os_guid,
go_data_ps TYPE REF TO zcl_ps_data,
go_data_agent TYPE REF TO zca_ps_data,
go_data_map_ps TYPE REF TO zcl_ps_data_map,
go_data_map_agent TYPE REF TO zca_ps_data_map,
go_exc TYPE REF TO cx_root.
go_data_agent = zca_ps_data=>agent.
go_data_map_agent = zca_ps_data_map=>agent.
TRY.
Check if there's already data with the business key on the DB
go_data_map_ps = go_data_map_agent->get_persistent(
i_data_ref = iv_data_ref
i_action = iv_action ).
... if there is then exit.
EXIT.
CATCH cx_root INTO go_exc.
ENDTRY.
TRY.
Create the data...
go_data_ps = go_data_agent->create_persistent(
i_root_guid = gv_blank_data_guid
i_req_date = iv_req_date ).
TRY.
... finally, write the new data to the data business key map table
go_data_map_ps = go_data_map_agent->create_persistent(
i_data_ref = iv_data_ref
i_action = iv_action
i_data_guid = go_data_ps ). "note1
CATCH cx_root INTO go_exc.
ENDTRY.
CATCH cx_os_object_not_found.
ENDTRY.
COMMIT WORK.
<-snip->
The fact that it is possible to pass the object GO_DATA_PS in the call to GO_DATA_MAP_AGENT (the line that I've put the comment "note1" on) indicates to me that the reference to the data persistent object can be written to the DB by the mapping persistent object. After executing the above code the mapping table object and class identifier fields are populated. Also, if multiple entries are written to the tables then the class identifier field in the mapping table is always the same and the object ID is different as expected.
However, the problem I have is if I read an object from the DB using the business key with the following code:
<-snip->
DATA:
gv_req_date type datum,
gv_data_guid TYPE os_guid,
go_data_ps TYPE REF TO zcl_ps_data,
go_data_agent TYPE REF TO zca_ps_data,
go_data_map_ps TYPE REF TO zcl_ps_data_map,
go_data_map_agent TYPE REF TO zca_ps_data_map,
go_exc TYPE REF TO cx_root.
go_data_agent = zca_ps_data=>agent.
go_data_map_agent = zca_ps_data_map=>agent.
TRY.
Read data mapping with the business key
go_data_map_ps = go_data_map_agent->get_persistent(
i_data_ref = iv_data_ref
i_action = iv_action ).
... then read the data.
TRY.
CALL METHOD go_data_map_ps->get_data_guid
RECEIVING
result = go_data_ps.
CATCH cx_os_object_not_found.
ENDTRY.
CATCH cx_root INTO go_exc.
ENDTRY.
<-snip->
At no point during this code are the attributes of the object of the persistent class for the data table populated with the contents of the fields of the data table referenced as the attribute of the mapping table. To clarify, when viewing the object in the debugger all the attributes of the mapping object that are simple table fields are populated with the values of the fields of in the mapping table, however, the attributes of the object that represents the persistent class for the data table are not populated with the fields of the data table. I had hoped that by reading the mapping table object the data object would automatically be populated. Is there another step I need to perform to populate the data object?
I'm sorry if the above is hard to follow. Without being able to provide screenshots it's difficult to explain.
If someone has managed to store references to persistent objects in a table and then read the references back could you list the steps you went through to create the persistent classes and include the code that reads the objects please? The code I have almost works, I must be just missing some subtle point...
Thanks in advance,
Steve.Hi Andrea,
The iObject being replicated at item level for Service Complaints is the SAP standard behaviour.
Generally we raise complaint refering to some sales or service issues. In your scenario you are trying to create a complaint based on an iObject, then you have to mention the corresponding product details. I dont see any business requirement not to copy the iObject product at the item level.
If you want it then I think only you have to write a Z program for it.
Hope this helps!
Regards,
Chethan -
Object as Reference not working..Please help..!!!
public class GG{
public static void main(String[] args) {
Integer i = new Integer(10);
System.out.println("Before Call:"+i);
change(i);
System.out.println("After Call:"+i);
public static void change(Integer x){
x=20;
Here the output is coming
Before Call:10
After Call:10
I am confused when i am passing an object in a function then why the value is not changed as objects are passed by reference??Java is pass-by-value. Recommended reading:
[http://www.javaranch.com/campfire/StoryCups.jsp]
[http://www.javaranch.com/campfire/StoryPassBy.jsp]
This topic has been done to death too many times already. I'm moving this thread to New to Java and locking this it. Jasvinder.Singh, please confine your questions to the New to Java forum until such time as you can regard yourself as a Java Programmer.
db -
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 muchYou 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.
Maybe you are looking for
-
HT204053 How can I create an Apple ID for my kids that are both under 13?
My parents bought my kids iPad Minis and they do not have Apple ID's. Ideally, I would like to link them to my account so they can use the tons of apps I've bought for them on my devices while allowing them to make purchases using the gift cardsthey'
-
Can't open DVD drive - Acer e15
Can't open DVD drive - Acer e15
-
CHARM with a 2 system landscape
Hello , we have only a 2 system landscape for our ERP systems. When I now click on the check button on the maintainance project. I receive an error : No consolidation system found for DEV-001 (project TEST_CHARM) No track for project TEST_CHARM with
-
Hi, I have recently installed Google Chrome. When it asked for access to my keychain for various passwords saved by Safari, I clicked "Allow Always" and without asking my keychain password, Chrome was given the right to use the particular passwords.
-
hi experts, i have a requirement in this the data is in 5 different columns and it is in text format, now i have to fetch this data and combine in to one column and have to export to the excel sheet when we press the export to excel button in dashboa