Immutable class

Can anyone tell me how we can create immutable class?

Prateek wrote:
Can anyone tell me how we can create immutable class?Do you have clear idea about the immutable class? String class is an immutable class. Look at the [url http://www.docjar.com/html/api/java/lang/String.java.html]String class for example and try by your own, and if you get struck then come back with your works.

Similar Messages

  • How To write Immutable Class

    Hi All
    can We write Immutable Class. If yes Then How.
    In my View It can be through final Keyword.

    An immutable class is simply a class whose internal
    data can't be changed once it's created. All fields
    will be declared private and no externally accessible
    methods will change them. That's all that's required.
    It's probably a good idea to declare the fields in
    the class as final, but it's not essential.
    Instead of mutator methods you typically have methods
    that create a new instance with some part of the data
    changed.Note that "final" has two meanings:
    1) a field must be set inside the constructor and nowhere else
    2) a method / class cannot be inherited
    You MUST forbid inheritance, or a subclass might override the methods and reenable mutability. This would have really nasty sideeffects.

  • Our own immutable class

    Hi,
    i have one requirement like ,need to develope my own immutable class like String class.if any one have sample code please post .
    Thanks,
    Anil.

    Make your class final. If you class has instance variables, make them private and final. Each instance variable's type itself should be immutable. If you do have mutable instance variables, then ensure when you write the class that you do not provide methods that mutate their values.
    - Saish

  • List of Immutable Classes?

    Is there a list of the classes in the standard lib. which are immutable (or claim to be immutable, or are designed to be immutable)?

    "need" is probably too strong a word.
    Some reflection based code I am writing can be made more efficient if I know that a class is immutable. For my own work I have an Immutable interface (no methods) which tells me what is immutable. Otherwise I check if the object is a String or a BigInteger (both are immutable I think) otherwise I treat it as if it is not-immutable. That is probably sufficient for the type of work I do.
    I was also curious to look into the source and see what techniques the gurus are using for immutable creatures.

  • Way to create an immutable class

    Is it possible to create a class which is immutable.

    @malcolmmc: although none of that would be technically necessary to ensure immutability.
    An immutable object is not supposed to change its "outside" state. Simplified, to me,
    public class Im {
      private int i;
      private int value v;
      public Im(int v) {
        this.v = v;
        int i = 0;
      public int get() {
        this.v++;
        this.i++;
        return this.v-this.i;
    }would still apper as immutable. Nevermind the overflow.
    Edit: or even worse:
    public class Im {
      private int value v;
      public Im() {
        this.v = 0;
      public void set(int i) {
        this.v = i;
      public int get() {
        return 42;
    }

  • Need help calling a method from an immutable class

    I'm having difficulties in calling a method from my class called Cabin to my main. Here's the code in my main              if(this is where i want my method hasKitchen() from my Cabin class)
                        System.out.println("There is a kitchen.");
                   else
                        System.out.println("There is not a kitchen.");
                   }and here's my method from my Cabin class:public boolean hasKitchen()
         return kitchen;
    }

    You should first have an instance of Cabin created by using
       Cabin c = ....
       if (c.hasKitchen()) {
         System.out.println("There is a kitchen.");
       } else {
            System.out.println("There is not a kitchen.");
       }

  • Immutable Vs Mutable Classes

    Hi.
    I want to know the following:
    1. What are immutable classes/objects?
    2. How to implement an immutable class?
    3. Is Math class immutable? I know it's final but is it immutable? what's the difference?
    4. Difference between Immutable/Mutable class - Implementation wise...
    Thanks

    Hi.
    I want to know the following:
    1. What are immutable classes/objects?An immutable object is one whose internal state (its fields or instance variables) cannot be changed once it has been created. An immutable class... I guess that would be a class whose objects are immutable.
    2. How to implement an immutable class?Make all instance variables private and do not provide any methods that change them.
    3. Is Math class immutable? I know it's final but is
    it immutable? what's the difference?The question doesn't apply, because you cannot create an object of class Math. The modifier "final" means that you cannot declare a subclass of the class; it has nothing to do with whether its objects are immutable.
    4. Difference between Immutable/Mutable class -
    Implementation wise...?
    >
    Thanks

  • Keeping a queue class immutable

    Hi,
    I recently got hooked on the concept of immutable classes. I'm not really sure why, but anyway...
    I have a class that queues up tasks to a worker thread for execution, which is currently immutable. However, I never implemented a way to stop the worker thread if I wanted the queue to shutdown, so I'm trying to come up with a way to do so while retaining the immutability of the class.
    Normally, I'd have a boolean value, and then set the boolean to false or true or whatever, and then the run() method in the worker thread would return. However, If I have to set a boolean, it would break the concept of immutability.
    So while this question may seem somewhat ridiculous, I'm more curious than anything to see if there's a way to solve this problem.
    Here's my queue class, with an incomplete shutdown() method, which I'd like to, in the future, "stop" the ThreadWorker thread:
    public final class ThreadQueue {
         private final ExecutorService pool;
         private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(5);
         public ThreadQueue() {
              pool = Executors.newSingleThreadExecutor();
              (new Thread(new ThreadWorker())).start();
         public synchronized void addToQueue(Runnable task) {
              try {
                   queue.put(task);
              } catch (InterruptedException ignored) {
         public void shutdown() {
         private final class ThreadWorker implements Runnable {
              public void run() {
                   for (;;) {
                        try {
                             pool.execute(queue.take());
                        } catch (InterruptedException ignored) {
    }If I'm just being pedantic with the whole immutability thing, so be it; I'm really curious.
    Any advice will be greatly appreciated.
    Thanks,
    Dan

    Well it looks as if I need to look up the definition of immutable again. I didn't think that adding things to a list would constitute changing the state of the object, but now that I think about it, that obviously does.
    Anyway, my question is answered; the question was a bit ridiculous like I had thought, but oh well.
    > >
    It seems to me tho that while shutdownNow could potentially stop the pool (which it seems is just 1 thread), it won't stop the other threads... BTW, all the threads seem to do is to loop and tell the single executor to run the next job... Are they actually running the jobs? Otherwise, why do you need more than 1 of them?
    As to this, shutting down the ExecutorService stops that thread, and it won't stop the thread running from ThreadWorker (which is why I changed my code as I'll show later). Anyway, the point of ThreadWorker is to execute each task in a "background" thread. Actually, since the ExecutorService runs in its own thread, it seems as if ThreadWorker is pretty worthless. If I added pool.execute(queue.take());it doesn't seem like it'll matter. Looks like I'll have to try that out and see what happens.
    Anyway, here's the most recent update of my code, with the new shutdownQueue() method and a new loop in ThreadWorker:
    public final class ThreadQueue {
         private final ExecutorService pool;
         private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(5);
         private volatile boolean stopThreadWorker;
         public ThreadQueue() {
              pool = Executors.newSingleThreadExecutor();
              stopThreadWorker = false;
              (new Thread(new ThreadWorker())).start();
         public synchronized void addToQueue(Runnable task) {
              try {
                   queue.put(task);
              } catch (InterruptedException ignored) {
         public void shutdownQueue() {
              stopThreadWorker = true;
              pool.shutdownNow();
         private final class ThreadWorker implements Runnable {
              public void run() {
                   while(stopThreadWorker) {
                        try {
                             pool.execute(queue.take());
                        } catch (InterruptedException ignored) {
    }Thanks for all the help!

  • Making a class immutable

    Ho w to make a class immutable??
    Thanx in advance

    Example
    import java.util.Date;
    * Planet is an immutable class, since there is no way to change
    * its state after construction.
    * @is.Immutable
    public final class Planet {
      public Planet (double aMass, String aName, Date aDateOfDiscovery) {
         fMass = aMass;
         fName = aName;
         //make a private copy of aDateOfDiscovery
         //this is the only way to keep the fDateOfDiscovery
         //field private, and shields this class from any changes
         //to the original aDateOfDiscovery object
         fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
      //gets but no sets, and no methods which change state
      public double getMass() {
        return fMass;
      public String getName() {
        return fName;
      * Returns a defensive copy of the field.
      * The caller of this method can do anything they want with the
      * returned Date object, without affecting the internals of this
      * class in any way.
      public Date getDateOfDiscovery() {
        return new Date(fDateOfDiscovery.getTime());
      // PRIVATE //
      * Primitive data is always immutable.
      private final double fMass;
      * An immutable object field. (String objects never change state.)
      private final String fName;
      * A mutable object field. In this case, the state of this mutable field
      * is to be changed only by this class. (In other cases, it makes perfect
      * sense to allow the state of a field to be changed outside the native
      * class; this is the case when a field acts as a "pointer" to an object
      * created elsewhere.)
      private final Date fDateOfDiscovery;

  • I want to make this class immutable. How to optimize performance?

    Hi,
    I designed an immutable class for other people to use. And I'm wondering if there's any way to optimize it for performance.
    ie.
    class MyImmutableList
      final List myList;
      public MyImmutableList(List list)
        myList = list;
      public MyImmutableList append(Item item)
        List copy = myList.copy();
        copy.append(item);
        return new MyImmutableList(copy);
    }But I find that many times, other people use the class like this:
    someList = someList.append(item);So in a case like this, append() is unnecessarily making a copy of the list.
    Is there anyway to optimize this?
    Thanks
    -Cuppo
    Edited by: CuppoJava on 20-Jul-2008 5:44 AM
    Edited by: CuppoJava on 20-Jul-2008 5:44 AM

    DrClap wrote:
    Well, of course, what else should they do when the method returns an ImmutableList?
    What I would do with that append() method would be to remove it from the API entirely. The class is supposed to be immutable? Then it doesn't need an append() method. Unless, of course, the append() method isn't meant to change the state of the object, which seems a bit, let's say, unintuitive. Returning a copy of the list with the object appended then wouldn't change the state of the object, but it would return a new object. Which in fact is what the code does. But why? I'm like those other people, I would do that too. I don't understand the purpose of the method.The Defence calls java.math.BigDecimal
    >
    BigDecimal, would it be fair to say, you are an immutable class?
    It would.
    Would it also be true to say that you have an add() method?
    I do
    And would it be fair to say that adding could be construed as a mutating operation?
    I suppose so
    And what does this method do, given that you claim to be immutable?
    It returns a new object which is the result of the add() operation
    Thankyou

  • 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

  • Is the instance fields have private accessibility in String class?

    Is the instance fields have private accessibility in an immutable class, such as the String class?
    also Could any one answer the following question,
    (This is the question I got in written exam for job recruitment)
    "Invoking a method can represent a significant amount of overhead in a program; as such, some compilers will perform an optimization called "method inlining." This optimization will remove a method call by copying the code inside the method into the calling method."
    Referring to the text above, which one of these statements is true?
    Choice 1 The performance benefits should be balanced against the increased chance of a RuntimeException.
    Choice 2 It allows the use of getter and setter methods to execute nearly as fast as direct access to member variables.
    Choice 3 This optimization will only occur if the relevant methods are declared volatile.
    Choice 4 The developer of inlined methods must copy and paste the code that is to be inlined into another method.
    Choice 5 It prevents code from executing in a way that follows object-oriented encapsulation.

    Sarwan_Gres wrote:
    Is the instance fields have private accessibility in an immutable class, such as the String class?Usually, but not always.
    "Invoking a method can represent a significant amount of overhead in a program; as such, some compilers will perform an optimization called "method inlining." This optimization will remove a method call by copying the code inside the method into the calling method."The java compiler does not inline methods so this is not relevant to Java. (The JVM does inline methods) The java compiler does inline constants known at compile time but it is a feature causes more trouble than good IMHO.

  • 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

  • Trade-offs of different Immutability designs

    Hi,
    I'm wondering what the trade-offs are for the following immutability designs:
    1) Object composition: a mutable class wraps an immutable class without any sort of inheritance. Example: String vs StringBuilder.
    2) Single interface with optional operations. Example: List throws UnsupportedOperationException when someone tries modifying an immutable list.
    3) Object inheritance: a mutable class extends an immutable class. Example: MutableString extends String by adding mutation methods to it. I could not find an example of this in the JDK.
    4) Are there other possible designs you're familiar with?
    Thank you,
    Gili

    Why would you need to do this? Why couldn't the mutable interface inherit from the immutable one?I was originally talking about classes where if the super is immutable then you quite literally cannot make it muttable (like String).
    But to answer the direction of the inheritance tree problem (mutable->immutable or vice versa), if Mutable extended Immutable it's then fundamentally not an Immutable breaking the "is a" rule, you have this problem with both directions of inheritance. More reason to steer clear of it I think.
    Deciding what modifiability to return/accept is an even more tricky business with both inherited route and with distinct classes, for example imagine the .iterator() method you would have to duplicate the methods to: mutableIterator() and immutableIterator(), this would plague your API designs and make it a royal pain to use.
    I meant unmodifiable class, not immutable.The discussion works for immutable and unmodifiables, though I think that converting between (im)mutables becomes even hairier (should be avoided) as users are lead to believe the internal class will never change, whereas unmodifiables allow the internal class data to change just not via API calls.
    I should explain that my "interest" here is the best way to introduce "turning modifiability on and off" (which is only a slight deviation to the original post). In my case, I've decided it's a must have feature.
    Why would the caller ever need to know whether a Collection is mutable or not?Where we've experienced this issue we've been designing an API that's not just a collection, more like heavyweight resources, where:
    -in certain cases we don't trust the user to give them access to the modifiable
    -where they can only receive/read from the resource and they should not alter it
    -to let them register interest in the resource before it's construction is finalised - ensuring they don't interrupt the finalisation process.
    -the API is about the same size as the collections API, which I think is bordering on the (to) largish size (if it's a small API I'd consider distinct classes).
    The decision was made to give them the ability to discover whether the resource was unmodifiable for two reasons:
    -code could be written (annoying that it's not "have to be" I agree) which would then be guaranteed not to fail unexpectedly later on (assuming compliance).
    -not having it meant that users are subtly encouraged to to write large chunks of code within an �ber try/catch to handle possible failures, which has it's obvious disadvantages.
    I also believe there should be some method of discovering whether the resource/collection is unmodifiable. Say you want fail fast behaviour for example, you have to call some modifiable method and deal with the resulting exception if it failed. And (slightly worse) try and undo it if it did work - which in some cases is impossible.
    In most cases (e.g. collections being used) this isn't required, as generally the collection's modifiability will stay the same for an apps lifetime and good testing (or the first time the error is discovered :) will out any mistakes which can be fixed once and for good.
    I think that Josh got it right when designing the collections framework, I can't see a better way of doing it given the size of the resulting API and ignoring the "not being able to discern modifiability" problem. Adding anything other than a tagging interface or simple checking method would have resulted in a seriously bloated API.
    I think the reason they didn't do anything about trying to discern modifiability was that, as collections don't change their modifiability (accepting composition), they probably decided, as you said, there's no benefit to adding the ability to check.
    I followed the link btw, it's interesting to get other peoples take on these issues, I constantly worry if I'm going down the right route. I am trying to get a few of our projects made open source so I can get other peoples feedback/input for that very reason.
    Wowsers, I also didn't realise I had this much to say about it, sorry.

  • Using bigdecimal class

    I was using Gregory-Leibniz series to calculate PI = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
    Something like:
    double pi = 0.0;      
           int limit = 3000000;      
           for (int i = 0, y = 1; i <= limit; y+=2, i++)
                     if (y == 1)
                          pi = 4;
                   else if (i % 2 == 0)
                          pi += (double)4/y;            
                     else
                          pi -= (double)4/y;                                                   
                     System.out.println(String.format("Loop %d: %.20f", i, pi));                                    }Then I realized PI isn't going to be totally accurate according to IEEE Standard for Binary Floating-Point Arithmetic that java math calculation uses, so I was trying to use BigDecimal class (new to me), this is what I got initally...
             BigDecimal pi = new BigDecimal("0.00");           
              int limit = 3000000;
              for (int i = 0, y = 1; i <= limit; y += 2, i++)
                  if (y == 1)
                          pi = new BigDecimal("4.0");
                   else if (i % 2 == 0)
                          pi = pi.add(new BigDecimal( Double.toString( (double) 4 / y )));
                     else
                          pi = pi.subtract(new BigDecimal( Double.toString( (double) 4 / y )));
                        System.out.println(String.format("Loop %d: %s", i, pi.toString()));                                       
    I realize that when I do the 4/y calculations involving both doubles... the result is probably stored according to the IEEE standards which is the thing to avoid... Is that correct? Is my PI result going to be accurate?
    I noticed with this one decimals up to the 22nd place are all filled with some numbers in the calculations compared with the first one involving only double number calculations which had zero's starting around the 15th decimal.
    Something like doesn't work and ends up with arithmeticexceptions...
    pi = pi.subtract(new BigDecimal("4").divide(new BigDecimal(Integer.toString(y))));
    So I'm actually confused about the right way of using BigDecimal class in this type of calculation to get accurate results. I do realize it's an immutable class and probably a bad idea to use it like this 3 million times in a loop.

    quoting from the API documentation on BigDecimal
    "The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriate MathContext object to the operation."
    That explains the arithmetic exceptions.
    You would be advised to choose your scale first, (that would be the number of decimal places that you want to be using for your calculation. ) Then use the BigDecimal constructors that use the scale value. Construct your BigDecimal 4 outside of the loop so that you are not constructing it over and over again. And finally, read the documentation on how the scale of the result will depend upon the scale of the components going in.
    A little reading and possibly re-reading of the documentation will help in the understanding of the BigDecimal class.

Maybe you are looking for

  • Slow Mount for App-V Packages

    Hi, I'm having an issue I first noticed with App-V 5 sequence packages deployed via ConfigMgr 2012 SP1 that are taking forever to mount. To rule out ConfigMgr i've manually copied an app-v package (around 1GB) and ran the following powershell command

  • Sap business one

    What are the differnce between query pld and query wizard in sap b one 2007

  • Getting screen error

    we are on the process of 4.6 to ECC6 upgrade system. we moved the changes to our Q system. now when we try to create order, we are getting some error messages 'Report RV13A603 has syntax error' 'Screen SAPMV13A 2603 is generated'.. Then next time whe

  • PopupMenu does not display

    Pleaase help me. popup menu doesn't display. Thanks. import java.io.*; import java.awt.*; import javax.swing.*; import java.util.Hashtable; import java.awt.event.*; import javax.swing.event.*; import java.applet.Applet; public class Combox extends JA

  • Script QPAC: how to get a process manager instance?

    Hi, I was desperately fiddling about the scripting QPAC, trying to get an instance of process manager. Since PATAbstractServiceEx is an abstract class, I cannot instantiate it and call its getContext().getProcessManager() methods. I also tried to acc