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;
$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];
java stack
New contributor
$endgroup$
add a comment |
$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];
java stack
New contributor
$endgroup$
2
$begingroup$
Your stack grows and never shrinks...
$endgroup$
– Boris the Spider
2 hours ago
add a comment |
$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];
java stack
New contributor
$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
java stack
New contributor
New contributor
edited 1 hour ago
Peter Mortensen
2621 silver badge7 bronze badges
2621 silver badge7 bronze badges
New contributor
asked 14 hours ago
JohnJohn
312 bronze badges
312 bronze badges
New contributor
New contributor
2
$begingroup$
Your stack grows and never shrinks...
$endgroup$
– Boris the Spider
2 hours ago
add a comment |
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
add a comment |
5 Answers
5
active
oldest
votes
$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
.
$endgroup$
add a comment |
$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:
- Rename
INCREMENTSIZE
toINCREMENT_SIZE
. It's customary, when naming constants using full caps, to separate words with underscores. - 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.
- 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.
- 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 pooledInteger
s. 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 tonull
; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using theArrays.copyOf
with a smaller second argument). - Guard against overflows. At some point,
list.length + INCREMENTSIZE
will overflow, and you'll getNegativeArraySizeException
fromArrays#copyOf
. Unfortunately, you can't have arrays which are indexed bylong
s, so best you can do is useInteger.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 howArrayDeque#grow(int)
andArrayDeque#newCapacity(int, int)
are implemented by OpenJDK here.
New contributor
$endgroup$
add a comment |
$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 int
s. 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.
$endgroup$
add a comment |
$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.
$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 yourpush
method (as @eckes is suggesting). Please note what thepush
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
|
show 1 more comment
$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.
$endgroup$
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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
.
$endgroup$
add a comment |
$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
.
$endgroup$
add a comment |
$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
.
$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
.
answered 14 hours ago
bhathiya-pererabhathiya-perera
2,4323 gold badges19 silver badges56 bronze badges
2,4323 gold badges19 silver badges56 bronze badges
add a comment |
add a comment |
$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:
- Rename
INCREMENTSIZE
toINCREMENT_SIZE
. It's customary, when naming constants using full caps, to separate words with underscores. - 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.
- 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.
- 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 pooledInteger
s. 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 tonull
; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using theArrays.copyOf
with a smaller second argument). - Guard against overflows. At some point,
list.length + INCREMENTSIZE
will overflow, and you'll getNegativeArraySizeException
fromArrays#copyOf
. Unfortunately, you can't have arrays which are indexed bylong
s, so best you can do is useInteger.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 howArrayDeque#grow(int)
andArrayDeque#newCapacity(int, int)
are implemented by OpenJDK here.
New contributor
$endgroup$
add a comment |
$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:
- Rename
INCREMENTSIZE
toINCREMENT_SIZE
. It's customary, when naming constants using full caps, to separate words with underscores. - 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.
- 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.
- 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 pooledInteger
s. 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 tonull
; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using theArrays.copyOf
with a smaller second argument). - Guard against overflows. At some point,
list.length + INCREMENTSIZE
will overflow, and you'll getNegativeArraySizeException
fromArrays#copyOf
. Unfortunately, you can't have arrays which are indexed bylong
s, so best you can do is useInteger.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 howArrayDeque#grow(int)
andArrayDeque#newCapacity(int, int)
are implemented by OpenJDK here.
New contributor
$endgroup$
add a comment |
$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:
- Rename
INCREMENTSIZE
toINCREMENT_SIZE
. It's customary, when naming constants using full caps, to separate words with underscores. - 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.
- 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.
- 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 pooledInteger
s. 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 tonull
; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using theArrays.copyOf
with a smaller second argument). - Guard against overflows. At some point,
list.length + INCREMENTSIZE
will overflow, and you'll getNegativeArraySizeException
fromArrays#copyOf
. Unfortunately, you can't have arrays which are indexed bylong
s, so best you can do is useInteger.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 howArrayDeque#grow(int)
andArrayDeque#newCapacity(int, int)
are implemented by OpenJDK here.
New contributor
$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:
- Rename
INCREMENTSIZE
toINCREMENT_SIZE
. It's customary, when naming constants using full caps, to separate words with underscores. - 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.
- 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.
- 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 pooledInteger
s. 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 tonull
; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using theArrays.copyOf
with a smaller second argument). - Guard against overflows. At some point,
list.length + INCREMENTSIZE
will overflow, and you'll getNegativeArraySizeException
fromArrays#copyOf
. Unfortunately, you can't have arrays which are indexed bylong
s, so best you can do is useInteger.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 howArrayDeque#grow(int)
andArrayDeque#newCapacity(int, int)
are implemented by OpenJDK here.
New contributor
New contributor
answered 3 hours ago
LukeLuke
1713 bronze badges
1713 bronze badges
New contributor
New contributor
add a comment |
add a comment |
$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 int
s. 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.
$endgroup$
add a comment |
$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 int
s. 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.
$endgroup$
add a comment |
$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 int
s. 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.
$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 int
s. 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.
answered 14 hours ago
GiantTreeGiantTree
4764 silver badges8 bronze badges
4764 silver badges8 bronze badges
add a comment |
add a comment |
$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.
$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 yourpush
method (as @eckes is suggesting). Please note what thepush
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
|
show 1 more comment
$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.
$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 yourpush
method (as @eckes is suggesting). Please note what thepush
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
|
show 1 more comment
$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.
$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.
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 yourpush
method (as @eckes is suggesting). Please note what thepush
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
|
show 1 more comment
$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 yourpush
method (as @eckes is suggesting). Please note what thepush
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
|
show 1 more comment
$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.
$endgroup$
add a comment |
$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.
$endgroup$
add a comment |
$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.
$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.
answered 44 mins ago
AlexanderAlexander
2361 silver badge8 bronze badges
2361 silver badge8 bronze badges
add a comment |
add a comment |
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.
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
2
$begingroup$
Your stack grows and never shrinks...
$endgroup$
– Boris the Spider
2 hours ago