Mutable objects

I am sorry if this isn't a right place for this question. I do not seam to find any information on how to make an object mutable.
If anyone can point me in the right direction I appreciate it.
Vitaly.

An Immutable object would be just as easy. Just dont allow any way of changing the instance variables. The constructor would be the only way to set them, when it is first created. You can, for example, make your own String class that is mutable as opposed to the current immutable version. Same thing with Boolean, Integer, etc. You could use the static methods of String, Boolean, Integer, etc in your mutable version as well.

Similar Messages

  • Immutable and mutable object

    Here I want to post some solutions to immutable and mutable objects. First I'll brifely discribe the case when only one type (immutable or mutable) is need accross the application. Then, I'll describe case when both types is using. And finally, the case when only some object can modify this object, while for others it is immutable one. That will be illusrated on the objects discribing current date as number milliseconds from Zero Epoch Era (January 1, 1970).
    Let's start from an exampe for Immutable Object.
    public final class ImmutableDate {
        private final long date;
        public ImmutableDate(long date){
             this.date= date;
        public long getDate(){
            return date;
    }The class is final, so it is imposible to extend it (if it is possible to extend it, it will be possible to add some mutable data-members to the class. Data-member is final to avoid changing (if it is Object it is just warning to programmer not to change it, compiler just can check that reference wasn't changed, but state of this data-member can be changed). There is no method that returns reference to the data-member outside the ImmutableDate. (if data-member was immutable object,it would be possible to return refference to it, if data-member was mutable object and it was possible to revieve reference to it, than it was possible to change the state of data-member through setter function).
    Now, lets consider that we need only MutableDate. The implementation is obvious:
    public  class MutableDate {
        private long date;
        public MutableDate (long date){
             this.date= date;
        public long getDate(){
            return date;
        public void setDate(long date){
          this.date=date;
    }This is regular class.
    The question is how what should I do in the case I need both[b ]Mutable and Immutable Object. It is possible to use the above way of implementation. But there are following problems wih this:
    * Code is not re-usable. For example, getDate() is implemented twice.
    * Implementation is closed to the interface.
    * There is no abstraction such a Date. Usable, when we doen't care whether object is mutable or immutable.
    It will be also nice to have a mechanism to recieve immutable copy from any object. It can be implemnted as getImmutableDate() function. This function is usable, when we have Date object (or MutableDate) at hand and want to store it in HashMap. So immutable copy is needed. It also usable as deffencive copy of MutableDate, if want one to transfer Date to simebody we don't want to change the state.
    Second and third points leads us to declare interfaces:
    public interface Date {
      public long getDate();
      public ImmutableDate getImmutableDate(); 
    public interface ImmutableDate extends Date  {
    public interface MutableDate extends Date {
      public void setDate(long date);
    public final class ImmutableDateImpl implements Date, ImmutableDate {
    public class MutableDateImpl  implements Date, MutableDate {
    }Lets talk more on the first point. In this short example it will look like it is not bug disadvantage. But think, that there are ten data members and setting other value isnot trivvial (for example, other private data members should be recalculated) and you'll realise that this is a problem. What solution OO proposed in such a cases? Right, inheritance. But there is one pitfalls here. Immutable object has to be final (see explanation above). So the only way to do this is to define some new class and inherit from him. It will be look like the following:
    abstract class AbstractDate implements Date  {
       protected long date;
       public AbstractDate(long date){
         this.date=date;
       public long getDate(){
         return date;
    public final class ImmutableDateImpl extends AbstractDate implements Date, ImmutableDate {
      public ImmutableDateImpl(long date){
        super(date);
      public final ImmutableDate getImmutableDate(){return this;}
    public class MutableDateImpl extends AbstractDate implements Date, MutableDate {
      public MutableDateImpl(long date){
        super(date);
      public void setDate(long date){
        this.date=date;
      public final ImmutableDate getImmutableDate(){
        return return new ImmutableDateImpl(date);
    }Note that AbstractDate is declare package-private. It is doing to avoid casting this type in the application. Note also that it is possible to cast immutable object to mutable (interface MutableDate doen't extends ImmutableDate, but Date). Note also that data memer is
    protected long date;That is not private, but protected and not final. It is a cost of getting re-usability. IMHO, It is not big price. Being protected is not a problem, IMHO. Final is more for programmer, rahter than to compiler (see explanation above). Only in the case of primitive data type compiler will inforce this. programmer can know, that in he shouldn't changed this value in AbstractDate, and ImmutableDate, and he can do it only in MutableDate.
    I want to write some words about getImmutableDate() function. This function is usable, when we have Date object (or MutableDate) at hand and want to store it in HashMap. So immutable copy is needed. It also usable as deffencive copy of MutableDate, if want one to transfer Date to somebody we don't want to change the state.
    Let consider the following scenarion. We are writting a game, say chess. There are two players, that plays, desk where they play, and environmemnt (arbiter) that enforces rules. One of the players is computer. From OO point of view the implementation has to the following. There is Desk that only Environment can modify it. ComputerPlayer has to be able only to view ("read") the Desk, but not to move figute ("write"). ComputerPlayer has to talk with Environment what he want to do, and Environmnet after confirmation should do it. Here desk is immutable object to everyone, but Environment.
    If we go back to our Date, the implementation of this scenario could be
    interface AlmostImmutableDate extends Date {
      public void setDate(long date);
    public class Class1 {
      public static ImmutableDate getImmutableDate(long date){return new AlmostImmutableDateImpl(date);}
      private static class AlmostImmutableDateImpl implements Date, ImmutableDate/*, AlmostImmutableDate*/ {
        private long date;
        public AlmostImmutableDate(long date){
          this.date=date;
        public long getDate(){
          return date;
        public void setDate(long date){
          this.date=date;
        public final ImmutableDate getImmutableDate(){
          return this;
    } Which such implementation only Class1 can modify AlmostImmutableDateImpl. Others even don't know about existance of this type (it is private static class).
    It is possible to extends somehow to the case, when not one object, but (a little) group of object can modify Date. See the code above with uncommented part. One way to this is to difine new interface, say AlmostImmutableDate, with package-private scope. AlmostImmutableDateImpl will implements this interface. So, all object that has the same package as AlmostImmutableDate will can to cast the object to this type and modify it.
    Note, that AlmostImmutableDate has to extend Date interface (or ImmutableDate), but not MutableDate! If it will extand MutableDate, than it wiil be possible to cast to MutableDate in any package.
    If there is no MutableDate object in the application, so AlmostImmutableDate is unique. If there is MutableDate object in the application and we want to construct such almost immutable object, so copy&paste is needed to declare AlmostImmutableDate interface.
    Summary.
    It is difficult to define really pair of immutable object and mutable object in Java. Implementation consuming time and not very clear. There are many points to remember about (for example, data-member is not final, or order of inheritance, immutable object has to be final, and so on).
    I want to ask. If these solutions are complete? That is, it is not possible to modify immutable object or almost immutable objects not in the package of AlmostImmutableInterface. Not using reflexion, of course.
    Is these solutions are not to complicated?
    What do you think about delcaration of the third class AbstractDate? Has it to implement date? Perhaps, it is possible to define Date as abstract class (as AbstractDate was)? What do you think about definning
    protected long date;in AbstractDate?
    What do you think about function getImmutableDate() defined in Date interface? Perhaps, it should be declared in other place (even other new interface) or shouldn't be delcare at all?

    It seems to me that you are over thinking the problem:
    Why not just:
    public interface Date {
        long getDate();
    public interface MutableDate extends Date {
        void setDate(long);
    public class ImmutableDate implements Date
        final long date;
        public ImmutableDate(long date){
             this.date= date;
        public ImmutableDate(Date date){
             this.date= date.getDate();
        public long getDate(){
            return date;
    public class ModifiableDate implements MutableDate
        final long date;
        public ModifiableDate(long date){
             this.date= date;
        public ModifiableDate(Date date){
             this.date = date.getDate();
        public long getDate(){
            return date;
        public void setDate(long date){
            this.date = date;
    }

  • Make a immutable extension to a mutable object.

    I have a mutable object that i would like to extend into a immutable version. The problem is in the mutable object's constructor, because it calls a method that mutates it's fields. What is everyone's thoughts on the following 'pattern'/solution below?. While this works perfectly fine for my tests and I'm pleased with the results I have an issue with calling it an immutable extension because i don't know if i can guarantee the immutability of it. Also please note that I do not want to change the mutable object's code as it is a java.util class and that the example below is only an example.
    public class MyMutableObject
        private int number;
        public MyMutableObject(){
            incrementNumber();
         * Mutates the current state!
        public void incrementNumber(){
            number++;
        public int getNumber(){
            return this.number;
    public final class MyImmutableObject extends MyMutableObject
         * synchronized should take care of the thread safty.
        public static synchronized MyImmutableObject newInstance(){
            return new MyImmutableObject();
         * when true the class is immutable.  we will take advantage of
         * the default value of a boolean(false) in order to determine
         * its state.
        private final boolean sealed;
        private MyImmutableObject(){
            super();
            sealed = true;
        @Override
        public void incrementNumber() {
            if (sealed)
                throw new UnsupportedOperationException("Object is Immutable!");
            super.incrementNumber();
    }

    How is this functionally different from
    public final class MyImmutableObject extends MutableObject {
        public MyImmutableObject() {
            super();
        public void incrementNumber()
        throws UnsupportedOperationException {
            throw new UnsupportedOperationException("Object is immutable");
    I see no value in either the sealed variable or the factory constructor.
    The synchronization, in particular, is a waste of time. Immutable classes
    are thread-safe by definition. As for the variable, since MyImmutableObject
    is final, and the only constructor seals it, there's no point.
    I'd say your class does enforce immutability as written. I'm not
    particularly fond of throwing exceptions when the immutable contract
    is violated, but you don't appear to have many other options.
    Also, ==tschodt

  • What is the use of mutable Objects ?

    Hi all,
    I want to know the use of mutable objects?
    Could u please help me ?
    regards,
    Nalini

    public class Sum {
        double value;
        public void add(double d) {
            value += d;
    }The sum class is mutable, since you can change it's value. The Integer class is an example of a class that's immutable. You can't change the value of an Integer after you have constructed the object.
    /Kaj

  • NPE Exception while getting mutable object

    I have an application (Model + ViewController). The ViewController is deployed as a jar file. The other application depends on the first project jar. The second application is a simple web application that responds to REST query. The first call is working fine. The second call throws an exception (NPE), and all following calls are working fine. I don't really understand the exception, what should I look for?
    SEVERE: Exception while getting mutable object
    java.lang.NullPointerException
            at oracle.mds.internal.persistence.NamespaceRulesImpl.<init>(NamespaceRulesImpl.java:123)
            at oracle.mds.internal.persistence.NamespaceRules.getNamespaceRulesObj(NamespaceRules.java:72)
            at oracle.mds.internal.util.ChangeUtil.convertToMOEvents(ChangeUtil.java:134)
            at oracle.mds.internal.notifications.EventNotificationManager.handleChanges(EventNotificationManager.java:354)
            at oracle.mds.internal.notifications.EventNotificationManager.handlePChanges(EventNotificationManager.java:251)
            at oracle.mds.core.MOState.signalStale(MOState.java:1185)
            at oracle.mds.core.MOState.signalStale(MOState.java:644)
            at oracle.mds.core.MOState.checkStalenessDocFromBuilder(MOState.java:739)
            at oracle.mds.core.MOState.getIsStaleLastModified(MOState.java:559)
            at oracle.mds.core.MOContent.getIsStaleLastModified(MOContent.java:277)
            at oracle.mds.core.ChainedMOContent.getIsStaleLastModified(ChainedMOContent.java:142)
            at oracle.mds.core.MetadataObject.isStale(MetadataObject.java:818)
            at oracle.adf.share.jndi.MDSBackingStore.obtainMetadataObject(MDSBackingStore.java:517)
            at oracle.adf.share.jndi.MDSBackingStore.getMOBean(MDSBackingStore.java:572)
            at oracle.bc4j.mbean.RuntimeMXBeanImpl.init(RuntimeMXBeanImpl.java:128)
            at oracle.bc4j.mbean.RuntimeMXBeanImpl.<init>(RuntimeMXBeanImpl.java:118)
            at oracle.bc4j.mbean.RuntimeMXBeanImpl.<init>(RuntimeMXBeanImpl.java:109)
            at oracle.bc4j.mbean.BC4JConfigLifeCycleCallBack.contextInitialized(BC4JConfigLifeCycleCallBack.java:160)
            at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:481)
            at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
            at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
            at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:181)
            at weblogic.servlet.internal.WebAppServletContext.reloadServletClassLoader(WebAppServletContext.java:3106)
            at weblogic.servlet.internal.FilterWrapper.reloadFilter(FilterWrapper.java:63)
            at weblogic.servlet.internal.FilterWrapper.checkForReload(FilterWrapper.java:104)
            at weblogic.servlet.internal.FilterWrapper.getFilter(FilterWrapper.java:41)
            at weblogic.servlet.internal.FilterChainImpl.add(FilterChainImpl.java:35)
            at weblogic.servlet.internal.FilterManager.getFilterChain(FilterManager.java:232)
            at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3727)
            at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
            at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
            at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
            at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
            at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
            at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
            at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
            at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
    Nov 25, 2013 1:44:58 PM oracle.bc4j.mbean.BC4JConfigLifeCycleCallBack contextInitialized
    WARNING: com/example/model/module/common/bc4j.xcfg: java.lang.NullPointerException

    The applications already existed when I started working on them, but I don't think the model projects were renamed or moved. I changed the original warning message "com/example/model/module/common/bc4j.xcfg". The warning message points to the correct bc4j.xml files.

  • Factory pattern returning shared mutable objects

    We have a non-EJB load-balanced environment of JSP/Business Objects
    with JMS synchronized caches. Here's an overview.
    Business objects stored in a custom in-process cache (one instance per JVM) and the caches are synchronized using JMS. The business objects are maintained through utility classes (not exactly factories) with the
    following pseudo -code logic
    public static Object getObject(Object id) {
    try {
    Get from cache...
    } catch(.. e) {
    load from database
    put it in cache.
    Currently we return the cached object "as-is" to the calling code. The objects being mutable this poses a risk of some JSP/bean inadvertently changing the cached copy. Although this is the fastest approach we have quickly realized that it is no longer safe.
    I am unable to find good patterns that address this common problem. Most patterns I have seen are very EJB centric and some of them boil down to the pseudo-code I have shown above. Which is not
    the solution but the problem itself!
    Is there anyway I can return an immutable instance of our objects in a generic way?. I know the alternatives..
    1) Clone. Create extra objects. It so happens the cached objects are actually shown in an end-user GUI tree on a web-page accessed by 200 concurrent users. cloning would create a copy per get call.
    2) Create an immutable and mutable version of the class and return only
    the immutable version. How do I ever get the mutable version with this approach
    This seems like a fairly common problem and I was wondering if anybody has solved this a little more elegantly then what I have presented above.

    2) Create an immutable and mutable version of the class and return onlythe immutable version. How do I ever get the mutable version with this approach
    The setter use no modifier or with protected modifier, the getter use public modifier.
    private String name;
    public String getName() {
       return name;
    String setName(String name) {
       this.name = name;
    }When the class is used outside the package, it is immutable, but it become mutable if accessed from class within the same package.
    This means, the cache manager class also need to be placed in the same package in order to gain mutable access.
    rgds,
    Alex

  • Reflecting updates to a ListCell that contains a mutable object

    Hi,
    I've seen many variants of this question, but unfortunately have not found the desired answer, so I thought to ask here. Apologies if missing something obvious!
    Objective:
    I start individual Tasks in batches. A ListCell reflects each Task, from initial request to eventual result. More batches can be submitted while one set is processing. When all processes of any batch is finished, they will eventually disappear from the ListView.
    As a result, I want a ListCell to reflect a Task, and reflect the transition from initial conception to eventual outcome.
    Predicament:
    I currently try this with an ObservableList of my own POJOs, each reflected using a custom ListCell extension.
    I have achieved this result, but it does not feel correct. First of all, I read that it is best practice not to change an ObservableList's objects under its feet. However, I have multiple threads working against the same list. With objects being added, removed and updated, it seemed safer to update the referenced object rather than try to manage synchronization to prevent concurrent modification issues. After all, I'm not really adding a new item, I'm wanting to update the representation of an item that is now in a finished state.
    Attempt details:
    I have achieved this by constructing an 'observableArrayList' with a Callback extractor. This Callback call method provides an Observable array containing an ObjectProperty, the property being a member variable of my POJO used in each ListCell. Each Task updates this object property with some result information at the end of its processing. This I believe ensure that change listeners are notified of updates to this POJO, via its ObjectProperty. (https://javafx-jira.kenai.com/browse/RT-15029)
    The ListCell constructed with this POJO is listening for updates, but I believe this is really to reflect additions and removals on the ObservableList that the ListView represents. However, in the case of updates, the private implementation of the ListCell updateItem method (javafx.scene.control.ListCell#updateItem) does not call the overridable updateItem method. This is because the object that caused the update is seen as equal to the object the ListCell currently holds (they're the same instance, so this is true). However, if the overridable updateItem method is never invoked, I can't get the custom ListCell to update its representation of the ListCell object that has changed since its last representation was rendered.
    If I make my custom POJO always return false in its overriden equals method, the overridable updateItem method is invoked and I get the opportunity to detect the change in the object and render a new representation. This works, but this feels wrong and like a hack.
    Can anyone help point me at the correct way of doing this please? Happy to provide more information if needed.
    Thanks,
    Louis

    If the changes in the ObservableList are to be reflected in the UI, you need to make these changes on the JavaFX Application Thread. Ensuring this happens (using Platform.runLater(...) if necessary) will also prevent any concurrent modification issues.
    I would approach this by binding the text property or graphic property (or both) of the custom ListCell to the appropriate properties of your POJO. Here's a simple example where I have a list view displaying a bunch of "counters" which count in a background thread. The cell display is updated when the state of the task changes. I introduced a counter property (which is a bit redundant; I could have used the progress property or message property) to demonstrate updating a property on the FX Application thread using Platform.runLater(...).
    Because ListCells can be reused, you need to account for the fact that the item (task) displayed may change during the lifecycle of the cell. You can do this using a listener to the itemProperty (which is what I did), or by overriding the updateItem(...) method.

  • Mutable and Immuatable Objects...Pl. Explain

    I would like to know what exactly are these mutable and immutable objects with respect to Java and how do they differ.

    Immutable objects are the one in which the same reference can't be assigned again and again if you perform any operation on it,in the other way it creates new reference whenever a method is called on that object.,example for that is the String object.
    Mutable objects are one in which the reference is not modified for any method on that object.For example StringBuffer object.,the same reference is used always.
    The basic difference is the reference you manipulate on.Immutable not possible to manipulate the same reference,Mutable possible to manipulate with the same reference.
    Hope this helps.
    Regards,
    Hari

  • Creation of  Immutable Object..

    Hi,
    How to create a immutable class which is having 'n number of Properties' .
    (One way i know With the help of constructor , all properties are initialized ).
    Thanks
    Dileep.

    mutabl objects are found only in java because its references are not final, mutable objects are shells, it is a terriable thing. james gosling said all objects should be made immutable if all possible.
    Most languages presume non-final variables, as does Java. I have no idea what you are referring to when you say a shell. JavaBean? There are certainly mutable objects that do more than just provide accessors and mutators. And Gosling's advice (if he said it, fine, I know others have and for other languages) is apt. Immutable objects are easier to understand and test. However, depending on what you are doing, a mutable object might give better performance. So, it is a guideline, not a stricture.
    making instance variables final is valid, data encapuslation is assumed. if your data is wide open, then there could be issues rising from there. simply making your data private but providing uncontrolled accesses via methods, such as straight getters/setters, equals to making your data public.
    Data encapsulation is not assumed, in fact it is more work to do so (granted, worth doing so, but it is anything but assumed by the language). And yes, if you provide a straight getter and setter ala a JavaBean, then yes, it is equivalent to having a public variable.
    please spend some time studying data encapsulation, it is one of the things that you need to understand; otherwise arnold will have to keep you simple!Now this is degenerating into gibberish.
    - Saish

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

  • Qualifing to be an immutible object

    Question: Is it possible to design an immutable object having final object references to mutable objects and still be 'viewed' as immutable.
    From the book JAVA Concurrency in Practice by Brian Goetz the following statements are made (that have confused me a bit):
    "Immutable objects ... can be safely accessed even when synchronization is not used to publish the object reference." (p.51)
    "... if [an object's] final fields refer to mutable objects, synchronization is still required to access the state of the objects they refer to."(p.52) To me this states that this type of object is not considered immutable.
    However, notice the final array object references to BigInteger[] from an example on page 49:
    @Immutable
    class OneValueCache {
        private final BigInteger lastNumber;
        private final BigInteger[] lastFactors;
        public OneValueCache( BigInteger i, BigInteger[] factors ) {
            lastNumber = i;
            lastFactors = Array.copyOf( factors, factors.length );
        public BigInteger[] getFactors( BigInteger i ) {
            if ( lastNumber == null || !lastNumber.equals( i ))
                return null;
            else
                return Arrays.copyOf( lastFactors, lastFactors.length );
    } Can all of the bigInteger[] lastFactors be considered final since the array object reference is final? Or is the immutability allowed since lastFactors is isolated with Arrays.copyOf() in both the constructor and getFactors() function? Does isolation of mutable objects references using techniques such as object cloning allow the object design to be immutable?
    Edited by: rbroersma on May 18, 2010 10:37 PM

    ejp wrote:
    So if the Object doesn't exist until the constructor returns what is the constructor is working on? Bringing the object into existence.He means, what is the constructor operating on or +manipulating, i.e. what is "this" referring to at that point?  Because you can pass "this" to other methods as if it existed.  And they can operate on it as if it existed...  So if you can do all those things to an object that doesn't exist, what good is your definition of existence?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • HELP on object duplication!

    Hi, I'm having some troubles when I try to make some local modifications while keeping the main array intact. My code looks like this
    classname [] P = new classname [constant]
    classname temp = P[2];
    .I noticed that whenever I change temp P[2] is also changed, so I tried this
    classname [] P = new classname [constant]
    classname [] Pcopy = P.clone();
    classname temp = Pcopy[2]
    .But even in this case P[2] was modified whenever an operation on temp is applied? How do I get around this nasty problem?
    Thanks a lot!!!

    abrli wrote:
    Hi, I'm having some troubles when I try to make some local modifications while keeping the main array intact. My code looks like this
    classname [] P = new classname [constant]
    classname temp = P[2];
    .I noticed that whenever I change temp P[2] is also changed, so I tried thisYes. Because P[2] and temp both hold references to the same object. A variable's value is never an object in Java, just a reference to an object. When you do x = y you're copying a reference, not an object, so now two references point to the same object.
    classname [] P = new classname [constant]
    classname [] Pcopy = P.clone();
    classname temp = Pcopy[2]
    .But even in this case P[2] was modified whenever an operation on temp is applied?Right. Because you've not copied the array, which contains references. You now have two arrays of references pointing to the same objects. P[0] points to the same object as Pcopy[0], etc.
    How do I get around this nasty problem?
    temp = P[2].clone();
    // OR
    temp = new WhateverThatClassIs(P[2]);Note that this will copy the object that P[2] points to, but if it has member variables that point to mutable objects, and if you might be changing those objects' states, and if you don't want that change to be reflected in both P[2] and temp, you'll need to clone or copy-construct those as well.
    Finally, as a side note, class names should start with uppercase and variables with lowercase. Constants should be all upper
    classname [] P = new classname [constant]
    // should be
    Classname [] p = new Classname [CONSTANT]
    Thanks a lot!!!

  • Strategy to make a mutable class immutable

    Hi,
    i posted this topic in the wrong forum:
    http://forum.java.sun.com/thread.jspa?threadID=5129395&messageID=9463016#9463016
    Could you help me?
    (I mentioned it already to the moderator)

    class Immutable {
    final Mutable delegatee;
    public Immutable(Mutable m) {
    delegatee = m; // <---- You must create adefensive copy of m first.
    ImmutableChild getChild() {
    return new ImmutableChild(delegatee.getChild());
    Note that you must create a defensive copy of the
    Mutable object in your Immutable constructor.
    Otherwise the caller can modify the supposedly
    Immutable through the Mutable reference it passed to
    the constructor.Like Stefan, i don't see your point. In this example, the only caller who can change the original mutable object, is the wrapper class. But that's no problem because the wrapper is designed by the creator of the mutable object.
    If you look to my specific problem, and you create a class SourceUnit, who has a reference to the class ImmutableAST, which is an immutable wrapper of my AST node class, i don't see how the client, that calls the method instanceOfSourceUnit.getImmutableAST() can modify the original abstract syntax tree (under condition that the the wrapper class does not delegate to original AST methodes that can change the state of the tree and that the fields it returns are also immutable (wrapper) classes)

  • Instance of Objects

    I try to save an instance of an object by creating a new object with the object's values at the time. I add the new object into a vector. When the value of the object changes, why does the new object in the vector also change? How could I store the instance as it is, not changing with when the object changes?
    Thanks.

    847604 wrote:
    I finally figured it out why the values have been changing. I was using a mutildimensional array and did not clone like the other things. Only a deep copy of the array would really finish the deal. When I did, no problem anymore.
    Thank you guys so much.
    One thing that I want to make sure about the clone() though. Since Cloneable is an interface, if I only use return super.clone(), what would it do? Do I actually have to do the following?
    @Override
    public Object clone() throws CloneNotSupportedException()
    Obj obj1 = (Obj) super.clone();
    }That's what you want, with a couple of additional bits of information.
    1) If your instance variables (non-static member variables) are all primitives and immutable objects, then that's all you need. However, if any of your instance variables are mutable reference types (like List or Date), then you'll probably want to explicitly copy those as well, to get a deep copy. (Of course, if you want your clone and original to refer to the same Date object, so that they both see changes to that object, then you wouldn't do that.)
    2) Not sure if "Obj" is supposed to be Object. If it is, there's never a need to cast to Object.
    3) Since 1.5, Java supports covariant return types, so you can declare clone() to return an instance of your class, rather than Object.
    public class Foo implements Cloneable {
      private int i; // no need for explicit deep clone of primitive
      private String s; // no need for explicit deep clone of immutable object
      private Date d; // need to explicitly deep clone mutable object
      public Foo clone() {
        Foo foo = (Foo) super.clone();
        foo.d = new Date(d); // or = d.clone(), or whatever approach is appropriate for copying a Date object
    }Likewise, if your Foo has any setters that can change any of its fields, then any class that has a Foo as a member would have to explicitly deep clone its Foo, which would then (by the above) take care of cloning its own mutable members.

  • Mutable NumberFormat - concurrency/thread safety using getCurrencyInstance

    Hi all,
    Maybe I'm starting to see ghosts but I think the method NumberFormat.getCurrencyInstance is very dangerous to use in a multi-threaded environment (the same applies to other getInstance() methods in DateFormat and NumberFormat as well).
    the javadoc for NumberFormat#getCurrencyInstance says:
    "public static NumberFormat getCurrencyInstance(Locale inLocale)
    Returns a currency format for the specified locale."
    This means that NumberFormat instances might be pooled, but it is open to the implementation. If I understand Sun's reference implementation correctly, it does always create a new instance. But other implementations might also use a pool.
    The issue is that NumberFormat instances are actually mutable objects, e.g. the method setCurrency() allows to set a currency which will be used when formatting a number.
    If multiple threads are manipulating the same mutable objects, the results will be undefinable, e.g.
    // thread 1:
    NumberFormat nf1 = NumberFormat.getCurrencyInstance(); // statement 1
    nf1.setCurrency(Currency.getInstance("EUR"); // statement 2
    System.out.println("thread 1:" + nf1.format(1000)); // statement 3
    // thread 2:
    NumberFormat nf2 = NumberFormat.getCurrencyInstance(); // statement 4
    nf2.setCurrency(Currency.getInstance("USD"); // statement 5
    System.out.println("thread 2:" + nf2.format(500)); // statement 6will print
    "thread 1: 1000 EUR"
    "thread 2: 500 USD"
    if statments are executed in the above order (1,2,3,4,5,6)
    but it will print
    "thread 1: 1000 USD"
    "thread 2: 500 USD"
    if the statements are executed in the order (1, 2, 4, 5, 3, 6)
    because nf1 and nf2 are the same objects (nf1 == nf2).
    I know that NumberFormats are not thread safe. Again from the javadoc:
    "Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. "
    My opinion:
    If number formats are not thread safe, the javadoc should at least define that getCurrencyInstance() will always create a new instance. That way getCurrencyInstance() could be used without any issues in compliant implementations.
    Any comments ?
    related bug parade links:
    http://developer.java.sun.com/developer/bugParade/bugs/4264153.html

    but what's the use of getInstance() if it MIGHT
    return pooled instances which I have to synchronize
    manually when I want to use them in a multithreaded
    environment. Because not everyone wants to use threads. So they
    shouldn't be subjected to the overhead.
    as far as I know the synchronized keyword
    is not permitted in EJB. Don't think so. Perhaps you mean synchronzing a ejb
    method which is not the same as synchronizing some
    code that occurs in a method.maybe I'm misreading the EJB spec:
    24.1.2 Programming restrictions
    "An enterprise Bean must not use thread synchronization primitives to synchronize execution of multiple instances."
    (ejb 2.0 from http://java.sun.com/products/ejb/docs.html)

Maybe you are looking for

  • Motorola Services Contact re-appears after delete and multiple times

    I have owned this Motorola Droid 3 for a week or so and I am having problems with Contacts. I have successful syncs with gmail, but I don't know why some contacts continue to reappear and continue to be added in spite of deleting them and in spite of

  • Webi report scheduling error

    Hi All, When I am refreshing Webi report, getting error: Invalid Prompt definition. See your Business Objects administrator. (Error: WIS 00005) Please help. Regards,

  • Problem with installing snow leopard 10.6.3... :(

    Hi everybody I wanted to install snow leopard 10.6.3. After loading first, I format hard drive and and installing first, it fell in a loop! in each loop, you should install mac os x! and I can't eject DVD. please help me!

  • How to default Concurrent Program delivery options to Email.

    As of r12.1.3, we have a new button in concurrent request submission window called "Delivery Opts" Clicking that button opens up a new window with delivery options.   Second tab contains the Email option. I have a need where a concurrent program is s

  • Apple to resolve my archive utility issue

    Apple has to resolve my archive utility issue with the error message  Error 32: Broken Pipe.  Apple says I have to re-install the Yosemite 10.10.2 software.  I am totally against re-installing the software for the simple reason that Archive Utility i