Stack class in Java 8Implement data structure overflow queueStack with 'getMinimum' operationMake a new design of Stack with a new functionStack implemented with a linked listImplementation of stackGeneric Stack (Array and Linked List) ImplementationA Stack TemplateObject-oriented calculator

Why can linguists decide which use of language is correct and which is not?

What is the name/purpose of this component?

How do Scrum teams manage their dependencies on other teams?

What is this sticking out of my wall?

How do I decide when to use MAPE, SMAPE and MASE for time series analysis on stock forecasting

Was Robin Hood's point of view ethically sound?

RANK used in 'where' returns invalid column, but exists in results set

How to calculate the proper layer height multiples?

Capacitors with same voltage, same capacitance, same temp, different diameter?

LGPL HDL in larger FPGA design

If every star in the universe except the Sun were destroyed, would we die?

What happens when a file that is 100% paged in to the page cache gets modified by another process

Problem with listing a directory to grep

Train between Vienna airport and city center

A word for decorative cords on uniforms

Is it unavoidable taking shortcuts in software development sometimes?

How can I finish my PhD?

Is there a "right" way to interpret a novel, if not, how do we make sure our novel is interpreted correctly?

How to descend a few exposed scrambling moves with minimal equipment?

How do I reference a custom counter that shows the section number?

How to find a reviewer/editor for my paper?

Are personality traits, ideals, bonds, and flaws required?

Owner keeps cutting corners and poaching workers for his other company

Are there any space probes or landers which regained communication after being lost?



Stack class in Java 8


Implement data structure overflow queueStack with 'getMinimum' operationMake a new design of Stack with a new functionStack implemented with a linked listImplementation of stackGeneric Stack (Array and Linked List) ImplementationA Stack TemplateObject-oriented calculator






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6












$begingroup$


I have a exercise where I have to write a Stack class with the push and pop methods. The code compiles and works as it should. Are there better practices to use in my code? Is there something I should avoid doing?



public class Stack 

private final int INCREMENTSIZE = 1024;
Integer position = 0;

int[] list = null;

public Stack()
list = new int[INCREMENTSIZE];


public void push(Integer i)
if(position == list.length)
list = Arrays.copyOf(list, list.length + INCREMENTSIZE);

list[position++] = i;


public Integer pop()
return list[--position];











share|improve this question









New contributor



John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$









  • 2




    $begingroup$
    Your stack grows and never shrinks...
    $endgroup$
    – Boris the Spider
    2 hours ago

















6












$begingroup$


I have a exercise where I have to write a Stack class with the push and pop methods. The code compiles and works as it should. Are there better practices to use in my code? Is there something I should avoid doing?



public class Stack 

private final int INCREMENTSIZE = 1024;
Integer position = 0;

int[] list = null;

public Stack()
list = new int[INCREMENTSIZE];


public void push(Integer i)
if(position == list.length)
list = Arrays.copyOf(list, list.length + INCREMENTSIZE);

list[position++] = i;


public Integer pop()
return list[--position];











share|improve this question









New contributor



John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$









  • 2




    $begingroup$
    Your stack grows and never shrinks...
    $endgroup$
    – Boris the Spider
    2 hours ago













6












6








6





$begingroup$


I have a exercise where I have to write a Stack class with the push and pop methods. The code compiles and works as it should. Are there better practices to use in my code? Is there something I should avoid doing?



public class Stack 

private final int INCREMENTSIZE = 1024;
Integer position = 0;

int[] list = null;

public Stack()
list = new int[INCREMENTSIZE];


public void push(Integer i)
if(position == list.length)
list = Arrays.copyOf(list, list.length + INCREMENTSIZE);

list[position++] = i;


public Integer pop()
return list[--position];











share|improve this question









New contributor



John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$




I have a exercise where I have to write a Stack class with the push and pop methods. The code compiles and works as it should. Are there better practices to use in my code? Is there something I should avoid doing?



public class Stack 

private final int INCREMENTSIZE = 1024;
Integer position = 0;

int[] list = null;

public Stack()
list = new int[INCREMENTSIZE];


public void push(Integer i)
if(position == list.length)
list = Arrays.copyOf(list, list.length + INCREMENTSIZE);

list[position++] = i;


public Integer pop()
return list[--position];








java stack






share|improve this question









New contributor



John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 1 hour ago









Peter Mortensen

2621 silver badge7 bronze badges




2621 silver badge7 bronze badges






New contributor



John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 14 hours ago









JohnJohn

312 bronze badges




312 bronze badges




New contributor



John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




John is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • 2




    $begingroup$
    Your stack grows and never shrinks...
    $endgroup$
    – Boris the Spider
    2 hours ago












  • 2




    $begingroup$
    Your stack grows and never shrinks...
    $endgroup$
    – Boris the Spider
    2 hours ago







2




2




$begingroup$
Your stack grows and never shrinks...
$endgroup$
– Boris the Spider
2 hours ago




$begingroup$
Your stack grows and never shrinks...
$endgroup$
– Boris the Spider
2 hours ago










5 Answers
5






active

oldest

votes


















8














$begingroup$

This looks good, However I suggest you properly indent the code.



Further suggestions:



I would change following




private final int INCREMENTSIZE = 1024;



to



private static final int INCREMENTSIZE = 1024;


Since you are not changing this in the constructor (to a new value) we might as well make it unique for the whole class.



I would change following




Integer position = 0;



to



private int position = 0;


There is no reason to have an Integer when int will do. We can also make it private.



For push and pop functions you can also use int's instead of Integer.






share|improve this answer









$endgroup$






















    7














    $begingroup$

    Other answers correctly point out that using primitive types and not mixing them with Objects (=int instead of Integer), reducing visibility wherever possible (=adding private modifier to position and list) and preventing popping from empty stack are good practices. There are a few more subtleties which can be improved:



    1. Rename INCREMENTSIZE to INCREMENT_SIZE. It's customary, when naming constants using full caps, to separate words with underscores.

    2. Consider growing a stack by multiplying current size and start small, e.g. instead having new size be current+increment, make it current*factor, where factor can be 1.5 or 2, or even decreased as the stack grows. If you're implementing a general purpose stack, you don't know how small or large the user will want it to be—incrementing by a constant might be an overkill or too small, while starting small and growing it in multiples will conserve memory if user needs a small stack, and will grow it in large enough increments later on if user needs to store many elements. The two approaches can be mixed and fine-tuned for best performance.

    3. Consider generifying the stack class so it can be a stack of anything, not just Integers. It's a small cost, but can be of large benefit.

    4. If you do store arbitrarily typed objects, beware of memory leaks! The pop function as it stands won't free memory if a user decides to empty the stack. It's a merely unconservative approach when dealing with primitives or small, usually pooled Integers. It can be a real problem when storing something heavyweight—your stack will keep a reference to something which the user has popped and prevent the garbage collector from collecting it (also see Effective Java 3rd ed., Item 7). To prevent this, when popping an element, set the value of the popped element in array to null; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using the Arrays.copyOf with a smaller second argument).

    5. Guard against overflows. At some point, list.length + INCREMENTSIZE will overflow, and you'll get NegativeArraySizeException from Arrays#copyOf. Unfortunately, you can't have arrays which are indexed by longs, so best you can do is use Integer.MAX_VALUE as the new size, and throw an exception (e.g. IllegalStateException with a helpful message) if the caller wants to add more items to stack after it's grown to MAX_VALUE. You can see how ArrayDeque#grow(int) and ArrayDeque#newCapacity(int, int) are implemented by OpenJDK here.





    share|improve this answer








    New contributor



    Luke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





    $endgroup$






















      6














      $begingroup$

      Your class is small and does what you said it should, that's good.

      However, there are a few things you could do better.



      1. Use primitive types unless the boxed ones are specifically needed:



      You are using the Integer type for counting the position and storing/returning data. If you actually used the fact, that it could be null, this would be acceptable use. However, any instance of null would break your code here. You are storing your integers in an int[], a primitive integer array. This leads to unboxing and a null reference will break your code.

      A position of null (not zero 0) also isn't making any sense in the context of your class.



      Use int instead of Integer unless you actually need null references.



      2. Reduce the visibility of member fields



      Other classes inside the same package as your class typically don't need access to your internal array. Make that array private.



      3. Think about what you want to store in your stack.



      Currently your stack only allows storing primitive ints. Maybe think about storing any type of data using generics. Extending your current class wouldn't be difficult.



      Other than that: Your code is concise, not too complicated and serves its purpose. Think about formatting the code using your IDE's formatter and add comments and documentation to your code.






      share|improve this answer









      $endgroup$






















        2














        $begingroup$

        Your class is good (for me I would rename the variable list as arr), but you should consider case where you call pop on an empty stack. In this case your method could throw an exception like the code below:



        public Integer pop()
        if (position == 0) throw new RuntimeException("Empty Stack");
        return list[--position];



        You can check from Java documentation that Stack pop() throws EmptyStackException, subclass of RuntimeException.






        share|improve this answer











        $endgroup$














        • $begingroup$
          INCREMENTSIZE is an unfortunate name for a full stack :p
          $endgroup$
          – dfhwze
          6 hours ago






        • 1




          $begingroup$
          @dfhwze lol, I realized now there is plenty of double meanings in my answer.
          $endgroup$
          – dariosicily
          6 hours ago






        • 3




          $begingroup$
          There is no sich thing as a Full stack in the original code
          $endgroup$
          – eckes
          6 hours ago






        • 1




          $begingroup$
          You need to remove the first line of your push method (as @eckes is suggesting). Please note what the push method is doing in the original code and you will see why. Cheers.
          $endgroup$
          – Ray Toal
          4 hours ago










        • $begingroup$
          The general idea of this answer, that one should make sure to handle edge cases like popping from an empty stack, is valid and worth pointing out. The specific advice and code you've suggested has several errors, however, and you appear not to have understood what the code you quoted and modified actually does.
          $endgroup$
          – Ilmari Karonen
          3 hours ago


















        0














        $begingroup$

        In addition to what other's have said:



        Your constant-increment growth scheme causes push operations to be amortized O(n). You should grow by a constant factor, as ArrayList does (1.5x, if I recall correctly). Even better, just don't use a primitive array at all, and use ArrayList instead.






        share|improve this answer









        $endgroup$

















          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );







          John is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded
















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f227655%2fstack-class-in-java-8%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8














          $begingroup$

          This looks good, However I suggest you properly indent the code.



          Further suggestions:



          I would change following




          private final int INCREMENTSIZE = 1024;



          to



          private static final int INCREMENTSIZE = 1024;


          Since you are not changing this in the constructor (to a new value) we might as well make it unique for the whole class.



          I would change following




          Integer position = 0;



          to



          private int position = 0;


          There is no reason to have an Integer when int will do. We can also make it private.



          For push and pop functions you can also use int's instead of Integer.






          share|improve this answer









          $endgroup$



















            8














            $begingroup$

            This looks good, However I suggest you properly indent the code.



            Further suggestions:



            I would change following




            private final int INCREMENTSIZE = 1024;



            to



            private static final int INCREMENTSIZE = 1024;


            Since you are not changing this in the constructor (to a new value) we might as well make it unique for the whole class.



            I would change following




            Integer position = 0;



            to



            private int position = 0;


            There is no reason to have an Integer when int will do. We can also make it private.



            For push and pop functions you can also use int's instead of Integer.






            share|improve this answer









            $endgroup$

















              8














              8










              8







              $begingroup$

              This looks good, However I suggest you properly indent the code.



              Further suggestions:



              I would change following




              private final int INCREMENTSIZE = 1024;



              to



              private static final int INCREMENTSIZE = 1024;


              Since you are not changing this in the constructor (to a new value) we might as well make it unique for the whole class.



              I would change following




              Integer position = 0;



              to



              private int position = 0;


              There is no reason to have an Integer when int will do. We can also make it private.



              For push and pop functions you can also use int's instead of Integer.






              share|improve this answer









              $endgroup$



              This looks good, However I suggest you properly indent the code.



              Further suggestions:



              I would change following




              private final int INCREMENTSIZE = 1024;



              to



              private static final int INCREMENTSIZE = 1024;


              Since you are not changing this in the constructor (to a new value) we might as well make it unique for the whole class.



              I would change following




              Integer position = 0;



              to



              private int position = 0;


              There is no reason to have an Integer when int will do. We can also make it private.



              For push and pop functions you can also use int's instead of Integer.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 14 hours ago









              bhathiya-pererabhathiya-perera

              2,4323 gold badges19 silver badges56 bronze badges




              2,4323 gold badges19 silver badges56 bronze badges


























                  7














                  $begingroup$

                  Other answers correctly point out that using primitive types and not mixing them with Objects (=int instead of Integer), reducing visibility wherever possible (=adding private modifier to position and list) and preventing popping from empty stack are good practices. There are a few more subtleties which can be improved:



                  1. Rename INCREMENTSIZE to INCREMENT_SIZE. It's customary, when naming constants using full caps, to separate words with underscores.

                  2. Consider growing a stack by multiplying current size and start small, e.g. instead having new size be current+increment, make it current*factor, where factor can be 1.5 or 2, or even decreased as the stack grows. If you're implementing a general purpose stack, you don't know how small or large the user will want it to be—incrementing by a constant might be an overkill or too small, while starting small and growing it in multiples will conserve memory if user needs a small stack, and will grow it in large enough increments later on if user needs to store many elements. The two approaches can be mixed and fine-tuned for best performance.

                  3. Consider generifying the stack class so it can be a stack of anything, not just Integers. It's a small cost, but can be of large benefit.

                  4. If you do store arbitrarily typed objects, beware of memory leaks! The pop function as it stands won't free memory if a user decides to empty the stack. It's a merely unconservative approach when dealing with primitives or small, usually pooled Integers. It can be a real problem when storing something heavyweight—your stack will keep a reference to something which the user has popped and prevent the garbage collector from collecting it (also see Effective Java 3rd ed., Item 7). To prevent this, when popping an element, set the value of the popped element in array to null; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using the Arrays.copyOf with a smaller second argument).

                  5. Guard against overflows. At some point, list.length + INCREMENTSIZE will overflow, and you'll get NegativeArraySizeException from Arrays#copyOf. Unfortunately, you can't have arrays which are indexed by longs, so best you can do is use Integer.MAX_VALUE as the new size, and throw an exception (e.g. IllegalStateException with a helpful message) if the caller wants to add more items to stack after it's grown to MAX_VALUE. You can see how ArrayDeque#grow(int) and ArrayDeque#newCapacity(int, int) are implemented by OpenJDK here.





                  share|improve this answer








                  New contributor



                  Luke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.





                  $endgroup$



















                    7














                    $begingroup$

                    Other answers correctly point out that using primitive types and not mixing them with Objects (=int instead of Integer), reducing visibility wherever possible (=adding private modifier to position and list) and preventing popping from empty stack are good practices. There are a few more subtleties which can be improved:



                    1. Rename INCREMENTSIZE to INCREMENT_SIZE. It's customary, when naming constants using full caps, to separate words with underscores.

                    2. Consider growing a stack by multiplying current size and start small, e.g. instead having new size be current+increment, make it current*factor, where factor can be 1.5 or 2, or even decreased as the stack grows. If you're implementing a general purpose stack, you don't know how small or large the user will want it to be—incrementing by a constant might be an overkill or too small, while starting small and growing it in multiples will conserve memory if user needs a small stack, and will grow it in large enough increments later on if user needs to store many elements. The two approaches can be mixed and fine-tuned for best performance.

                    3. Consider generifying the stack class so it can be a stack of anything, not just Integers. It's a small cost, but can be of large benefit.

                    4. If you do store arbitrarily typed objects, beware of memory leaks! The pop function as it stands won't free memory if a user decides to empty the stack. It's a merely unconservative approach when dealing with primitives or small, usually pooled Integers. It can be a real problem when storing something heavyweight—your stack will keep a reference to something which the user has popped and prevent the garbage collector from collecting it (also see Effective Java 3rd ed., Item 7). To prevent this, when popping an element, set the value of the popped element in array to null; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using the Arrays.copyOf with a smaller second argument).

                    5. Guard against overflows. At some point, list.length + INCREMENTSIZE will overflow, and you'll get NegativeArraySizeException from Arrays#copyOf. Unfortunately, you can't have arrays which are indexed by longs, so best you can do is use Integer.MAX_VALUE as the new size, and throw an exception (e.g. IllegalStateException with a helpful message) if the caller wants to add more items to stack after it's grown to MAX_VALUE. You can see how ArrayDeque#grow(int) and ArrayDeque#newCapacity(int, int) are implemented by OpenJDK here.





                    share|improve this answer








                    New contributor



                    Luke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.





                    $endgroup$

















                      7














                      7










                      7







                      $begingroup$

                      Other answers correctly point out that using primitive types and not mixing them with Objects (=int instead of Integer), reducing visibility wherever possible (=adding private modifier to position and list) and preventing popping from empty stack are good practices. There are a few more subtleties which can be improved:



                      1. Rename INCREMENTSIZE to INCREMENT_SIZE. It's customary, when naming constants using full caps, to separate words with underscores.

                      2. Consider growing a stack by multiplying current size and start small, e.g. instead having new size be current+increment, make it current*factor, where factor can be 1.5 or 2, or even decreased as the stack grows. If you're implementing a general purpose stack, you don't know how small or large the user will want it to be—incrementing by a constant might be an overkill or too small, while starting small and growing it in multiples will conserve memory if user needs a small stack, and will grow it in large enough increments later on if user needs to store many elements. The two approaches can be mixed and fine-tuned for best performance.

                      3. Consider generifying the stack class so it can be a stack of anything, not just Integers. It's a small cost, but can be of large benefit.

                      4. If you do store arbitrarily typed objects, beware of memory leaks! The pop function as it stands won't free memory if a user decides to empty the stack. It's a merely unconservative approach when dealing with primitives or small, usually pooled Integers. It can be a real problem when storing something heavyweight—your stack will keep a reference to something which the user has popped and prevent the garbage collector from collecting it (also see Effective Java 3rd ed., Item 7). To prevent this, when popping an element, set the value of the popped element in array to null; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using the Arrays.copyOf with a smaller second argument).

                      5. Guard against overflows. At some point, list.length + INCREMENTSIZE will overflow, and you'll get NegativeArraySizeException from Arrays#copyOf. Unfortunately, you can't have arrays which are indexed by longs, so best you can do is use Integer.MAX_VALUE as the new size, and throw an exception (e.g. IllegalStateException with a helpful message) if the caller wants to add more items to stack after it's grown to MAX_VALUE. You can see how ArrayDeque#grow(int) and ArrayDeque#newCapacity(int, int) are implemented by OpenJDK here.





                      share|improve this answer








                      New contributor



                      Luke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.





                      $endgroup$



                      Other answers correctly point out that using primitive types and not mixing them with Objects (=int instead of Integer), reducing visibility wherever possible (=adding private modifier to position and list) and preventing popping from empty stack are good practices. There are a few more subtleties which can be improved:



                      1. Rename INCREMENTSIZE to INCREMENT_SIZE. It's customary, when naming constants using full caps, to separate words with underscores.

                      2. Consider growing a stack by multiplying current size and start small, e.g. instead having new size be current+increment, make it current*factor, where factor can be 1.5 or 2, or even decreased as the stack grows. If you're implementing a general purpose stack, you don't know how small or large the user will want it to be—incrementing by a constant might be an overkill or too small, while starting small and growing it in multiples will conserve memory if user needs a small stack, and will grow it in large enough increments later on if user needs to store many elements. The two approaches can be mixed and fine-tuned for best performance.

                      3. Consider generifying the stack class so it can be a stack of anything, not just Integers. It's a small cost, but can be of large benefit.

                      4. If you do store arbitrarily typed objects, beware of memory leaks! The pop function as it stands won't free memory if a user decides to empty the stack. It's a merely unconservative approach when dealing with primitives or small, usually pooled Integers. It can be a real problem when storing something heavyweight—your stack will keep a reference to something which the user has popped and prevent the garbage collector from collecting it (also see Effective Java 3rd ed., Item 7). To prevent this, when popping an element, set the value of the popped element in array to null; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using the Arrays.copyOf with a smaller second argument).

                      5. Guard against overflows. At some point, list.length + INCREMENTSIZE will overflow, and you'll get NegativeArraySizeException from Arrays#copyOf. Unfortunately, you can't have arrays which are indexed by longs, so best you can do is use Integer.MAX_VALUE as the new size, and throw an exception (e.g. IllegalStateException with a helpful message) if the caller wants to add more items to stack after it's grown to MAX_VALUE. You can see how ArrayDeque#grow(int) and ArrayDeque#newCapacity(int, int) are implemented by OpenJDK here.






                      share|improve this answer








                      New contributor



                      Luke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.








                      share|improve this answer



                      share|improve this answer






                      New contributor



                      Luke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.








                      answered 3 hours ago









                      LukeLuke

                      1713 bronze badges




                      1713 bronze badges




                      New contributor



                      Luke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.




                      New contributor




                      Luke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.


























                          6














                          $begingroup$

                          Your class is small and does what you said it should, that's good.

                          However, there are a few things you could do better.



                          1. Use primitive types unless the boxed ones are specifically needed:



                          You are using the Integer type for counting the position and storing/returning data. If you actually used the fact, that it could be null, this would be acceptable use. However, any instance of null would break your code here. You are storing your integers in an int[], a primitive integer array. This leads to unboxing and a null reference will break your code.

                          A position of null (not zero 0) also isn't making any sense in the context of your class.



                          Use int instead of Integer unless you actually need null references.



                          2. Reduce the visibility of member fields



                          Other classes inside the same package as your class typically don't need access to your internal array. Make that array private.



                          3. Think about what you want to store in your stack.



                          Currently your stack only allows storing primitive ints. Maybe think about storing any type of data using generics. Extending your current class wouldn't be difficult.



                          Other than that: Your code is concise, not too complicated and serves its purpose. Think about formatting the code using your IDE's formatter and add comments and documentation to your code.






                          share|improve this answer









                          $endgroup$



















                            6














                            $begingroup$

                            Your class is small and does what you said it should, that's good.

                            However, there are a few things you could do better.



                            1. Use primitive types unless the boxed ones are specifically needed:



                            You are using the Integer type for counting the position and storing/returning data. If you actually used the fact, that it could be null, this would be acceptable use. However, any instance of null would break your code here. You are storing your integers in an int[], a primitive integer array. This leads to unboxing and a null reference will break your code.

                            A position of null (not zero 0) also isn't making any sense in the context of your class.



                            Use int instead of Integer unless you actually need null references.



                            2. Reduce the visibility of member fields



                            Other classes inside the same package as your class typically don't need access to your internal array. Make that array private.



                            3. Think about what you want to store in your stack.



                            Currently your stack only allows storing primitive ints. Maybe think about storing any type of data using generics. Extending your current class wouldn't be difficult.



                            Other than that: Your code is concise, not too complicated and serves its purpose. Think about formatting the code using your IDE's formatter and add comments and documentation to your code.






                            share|improve this answer









                            $endgroup$

















                              6














                              6










                              6







                              $begingroup$

                              Your class is small and does what you said it should, that's good.

                              However, there are a few things you could do better.



                              1. Use primitive types unless the boxed ones are specifically needed:



                              You are using the Integer type for counting the position and storing/returning data. If you actually used the fact, that it could be null, this would be acceptable use. However, any instance of null would break your code here. You are storing your integers in an int[], a primitive integer array. This leads to unboxing and a null reference will break your code.

                              A position of null (not zero 0) also isn't making any sense in the context of your class.



                              Use int instead of Integer unless you actually need null references.



                              2. Reduce the visibility of member fields



                              Other classes inside the same package as your class typically don't need access to your internal array. Make that array private.



                              3. Think about what you want to store in your stack.



                              Currently your stack only allows storing primitive ints. Maybe think about storing any type of data using generics. Extending your current class wouldn't be difficult.



                              Other than that: Your code is concise, not too complicated and serves its purpose. Think about formatting the code using your IDE's formatter and add comments and documentation to your code.






                              share|improve this answer









                              $endgroup$



                              Your class is small and does what you said it should, that's good.

                              However, there are a few things you could do better.



                              1. Use primitive types unless the boxed ones are specifically needed:



                              You are using the Integer type for counting the position and storing/returning data. If you actually used the fact, that it could be null, this would be acceptable use. However, any instance of null would break your code here. You are storing your integers in an int[], a primitive integer array. This leads to unboxing and a null reference will break your code.

                              A position of null (not zero 0) also isn't making any sense in the context of your class.



                              Use int instead of Integer unless you actually need null references.



                              2. Reduce the visibility of member fields



                              Other classes inside the same package as your class typically don't need access to your internal array. Make that array private.



                              3. Think about what you want to store in your stack.



                              Currently your stack only allows storing primitive ints. Maybe think about storing any type of data using generics. Extending your current class wouldn't be difficult.



                              Other than that: Your code is concise, not too complicated and serves its purpose. Think about formatting the code using your IDE's formatter and add comments and documentation to your code.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 14 hours ago









                              GiantTreeGiantTree

                              4764 silver badges8 bronze badges




                              4764 silver badges8 bronze badges
























                                  2














                                  $begingroup$

                                  Your class is good (for me I would rename the variable list as arr), but you should consider case where you call pop on an empty stack. In this case your method could throw an exception like the code below:



                                  public Integer pop()
                                  if (position == 0) throw new RuntimeException("Empty Stack");
                                  return list[--position];



                                  You can check from Java documentation that Stack pop() throws EmptyStackException, subclass of RuntimeException.






                                  share|improve this answer











                                  $endgroup$














                                  • $begingroup$
                                    INCREMENTSIZE is an unfortunate name for a full stack :p
                                    $endgroup$
                                    – dfhwze
                                    6 hours ago






                                  • 1




                                    $begingroup$
                                    @dfhwze lol, I realized now there is plenty of double meanings in my answer.
                                    $endgroup$
                                    – dariosicily
                                    6 hours ago






                                  • 3




                                    $begingroup$
                                    There is no sich thing as a Full stack in the original code
                                    $endgroup$
                                    – eckes
                                    6 hours ago






                                  • 1




                                    $begingroup$
                                    You need to remove the first line of your push method (as @eckes is suggesting). Please note what the push method is doing in the original code and you will see why. Cheers.
                                    $endgroup$
                                    – Ray Toal
                                    4 hours ago










                                  • $begingroup$
                                    The general idea of this answer, that one should make sure to handle edge cases like popping from an empty stack, is valid and worth pointing out. The specific advice and code you've suggested has several errors, however, and you appear not to have understood what the code you quoted and modified actually does.
                                    $endgroup$
                                    – Ilmari Karonen
                                    3 hours ago















                                  2














                                  $begingroup$

                                  Your class is good (for me I would rename the variable list as arr), but you should consider case where you call pop on an empty stack. In this case your method could throw an exception like the code below:



                                  public Integer pop()
                                  if (position == 0) throw new RuntimeException("Empty Stack");
                                  return list[--position];



                                  You can check from Java documentation that Stack pop() throws EmptyStackException, subclass of RuntimeException.






                                  share|improve this answer











                                  $endgroup$














                                  • $begingroup$
                                    INCREMENTSIZE is an unfortunate name for a full stack :p
                                    $endgroup$
                                    – dfhwze
                                    6 hours ago






                                  • 1




                                    $begingroup$
                                    @dfhwze lol, I realized now there is plenty of double meanings in my answer.
                                    $endgroup$
                                    – dariosicily
                                    6 hours ago






                                  • 3




                                    $begingroup$
                                    There is no sich thing as a Full stack in the original code
                                    $endgroup$
                                    – eckes
                                    6 hours ago






                                  • 1




                                    $begingroup$
                                    You need to remove the first line of your push method (as @eckes is suggesting). Please note what the push method is doing in the original code and you will see why. Cheers.
                                    $endgroup$
                                    – Ray Toal
                                    4 hours ago










                                  • $begingroup$
                                    The general idea of this answer, that one should make sure to handle edge cases like popping from an empty stack, is valid and worth pointing out. The specific advice and code you've suggested has several errors, however, and you appear not to have understood what the code you quoted and modified actually does.
                                    $endgroup$
                                    – Ilmari Karonen
                                    3 hours ago













                                  2














                                  2










                                  2







                                  $begingroup$

                                  Your class is good (for me I would rename the variable list as arr), but you should consider case where you call pop on an empty stack. In this case your method could throw an exception like the code below:



                                  public Integer pop()
                                  if (position == 0) throw new RuntimeException("Empty Stack");
                                  return list[--position];



                                  You can check from Java documentation that Stack pop() throws EmptyStackException, subclass of RuntimeException.






                                  share|improve this answer











                                  $endgroup$



                                  Your class is good (for me I would rename the variable list as arr), but you should consider case where you call pop on an empty stack. In this case your method could throw an exception like the code below:



                                  public Integer pop()
                                  if (position == 0) throw new RuntimeException("Empty Stack");
                                  return list[--position];



                                  You can check from Java documentation that Stack pop() throws EmptyStackException, subclass of RuntimeException.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited 3 hours ago

























                                  answered 6 hours ago









                                  dariosicilydariosicily

                                  3447 bronze badges




                                  3447 bronze badges














                                  • $begingroup$
                                    INCREMENTSIZE is an unfortunate name for a full stack :p
                                    $endgroup$
                                    – dfhwze
                                    6 hours ago






                                  • 1




                                    $begingroup$
                                    @dfhwze lol, I realized now there is plenty of double meanings in my answer.
                                    $endgroup$
                                    – dariosicily
                                    6 hours ago






                                  • 3




                                    $begingroup$
                                    There is no sich thing as a Full stack in the original code
                                    $endgroup$
                                    – eckes
                                    6 hours ago






                                  • 1




                                    $begingroup$
                                    You need to remove the first line of your push method (as @eckes is suggesting). Please note what the push method is doing in the original code and you will see why. Cheers.
                                    $endgroup$
                                    – Ray Toal
                                    4 hours ago










                                  • $begingroup$
                                    The general idea of this answer, that one should make sure to handle edge cases like popping from an empty stack, is valid and worth pointing out. The specific advice and code you've suggested has several errors, however, and you appear not to have understood what the code you quoted and modified actually does.
                                    $endgroup$
                                    – Ilmari Karonen
                                    3 hours ago
















                                  • $begingroup$
                                    INCREMENTSIZE is an unfortunate name for a full stack :p
                                    $endgroup$
                                    – dfhwze
                                    6 hours ago






                                  • 1




                                    $begingroup$
                                    @dfhwze lol, I realized now there is plenty of double meanings in my answer.
                                    $endgroup$
                                    – dariosicily
                                    6 hours ago






                                  • 3




                                    $begingroup$
                                    There is no sich thing as a Full stack in the original code
                                    $endgroup$
                                    – eckes
                                    6 hours ago






                                  • 1




                                    $begingroup$
                                    You need to remove the first line of your push method (as @eckes is suggesting). Please note what the push method is doing in the original code and you will see why. Cheers.
                                    $endgroup$
                                    – Ray Toal
                                    4 hours ago










                                  • $begingroup$
                                    The general idea of this answer, that one should make sure to handle edge cases like popping from an empty stack, is valid and worth pointing out. The specific advice and code you've suggested has several errors, however, and you appear not to have understood what the code you quoted and modified actually does.
                                    $endgroup$
                                    – Ilmari Karonen
                                    3 hours ago















                                  $begingroup$
                                  INCREMENTSIZE is an unfortunate name for a full stack :p
                                  $endgroup$
                                  – dfhwze
                                  6 hours ago




                                  $begingroup$
                                  INCREMENTSIZE is an unfortunate name for a full stack :p
                                  $endgroup$
                                  – dfhwze
                                  6 hours ago




                                  1




                                  1




                                  $begingroup$
                                  @dfhwze lol, I realized now there is plenty of double meanings in my answer.
                                  $endgroup$
                                  – dariosicily
                                  6 hours ago




                                  $begingroup$
                                  @dfhwze lol, I realized now there is plenty of double meanings in my answer.
                                  $endgroup$
                                  – dariosicily
                                  6 hours ago




                                  3




                                  3




                                  $begingroup$
                                  There is no sich thing as a Full stack in the original code
                                  $endgroup$
                                  – eckes
                                  6 hours ago




                                  $begingroup$
                                  There is no sich thing as a Full stack in the original code
                                  $endgroup$
                                  – eckes
                                  6 hours ago




                                  1




                                  1




                                  $begingroup$
                                  You need to remove the first line of your push method (as @eckes is suggesting). Please note what the push method is doing in the original code and you will see why. Cheers.
                                  $endgroup$
                                  – Ray Toal
                                  4 hours ago




                                  $begingroup$
                                  You need to remove the first line of your push method (as @eckes is suggesting). Please note what the push method is doing in the original code and you will see why. Cheers.
                                  $endgroup$
                                  – Ray Toal
                                  4 hours ago












                                  $begingroup$
                                  The general idea of this answer, that one should make sure to handle edge cases like popping from an empty stack, is valid and worth pointing out. The specific advice and code you've suggested has several errors, however, and you appear not to have understood what the code you quoted and modified actually does.
                                  $endgroup$
                                  – Ilmari Karonen
                                  3 hours ago




                                  $begingroup$
                                  The general idea of this answer, that one should make sure to handle edge cases like popping from an empty stack, is valid and worth pointing out. The specific advice and code you've suggested has several errors, however, and you appear not to have understood what the code you quoted and modified actually does.
                                  $endgroup$
                                  – Ilmari Karonen
                                  3 hours ago











                                  0














                                  $begingroup$

                                  In addition to what other's have said:



                                  Your constant-increment growth scheme causes push operations to be amortized O(n). You should grow by a constant factor, as ArrayList does (1.5x, if I recall correctly). Even better, just don't use a primitive array at all, and use ArrayList instead.






                                  share|improve this answer









                                  $endgroup$



















                                    0














                                    $begingroup$

                                    In addition to what other's have said:



                                    Your constant-increment growth scheme causes push operations to be amortized O(n). You should grow by a constant factor, as ArrayList does (1.5x, if I recall correctly). Even better, just don't use a primitive array at all, and use ArrayList instead.






                                    share|improve this answer









                                    $endgroup$

















                                      0














                                      0










                                      0







                                      $begingroup$

                                      In addition to what other's have said:



                                      Your constant-increment growth scheme causes push operations to be amortized O(n). You should grow by a constant factor, as ArrayList does (1.5x, if I recall correctly). Even better, just don't use a primitive array at all, and use ArrayList instead.






                                      share|improve this answer









                                      $endgroup$



                                      In addition to what other's have said:



                                      Your constant-increment growth scheme causes push operations to be amortized O(n). You should grow by a constant factor, as ArrayList does (1.5x, if I recall correctly). Even better, just don't use a primitive array at all, and use ArrayList instead.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 44 mins ago









                                      AlexanderAlexander

                                      2361 silver badge8 bronze badges




                                      2361 silver badge8 bronze badges
























                                          John is a new contributor. Be nice, and check out our Code of Conduct.









                                          draft saved

                                          draft discarded

















                                          John is a new contributor. Be nice, and check out our Code of Conduct.












                                          John is a new contributor. Be nice, and check out our Code of Conduct.











                                          John is a new contributor. Be nice, and check out our Code of Conduct.














                                          Thanks for contributing an answer to Code Review Stack Exchange!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          Use MathJax to format equations. MathJax reference.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f227655%2fstack-class-in-java-8%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                          Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                          199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單