This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm trying to implement linked Lists.
I therefore have this first class, called List, which represents one element
package list;
/**
* Linked list with int values.
*
* The empty list is represented by a null reference.
*/
public class List {
public int value;
public List next;
/**
* Creates a new list
*
* #param value value of the head of the list
* #param next reference to rest of the list; may be null
*/
public List(int value, List next)
{
this.value = value;
this.next = next;
}
}
and the linked list class itself which contains the following method
public static int size(List list)
{
if(list==null) return 0;
else return size(list.next)+1;
}
so far everything works. But if I try
public static int size(List list)
{
if(list.next==null) return 1;
else return size(list.next)+1;
}
i get a NullPointerException...
I have no Idea why this shouldn't work since list.next should a one point be a reference to the null pointer and end the recursion.
Therefore size(null.next) should never be called.
I apologise for the bad english and am grateful for any help
Your original size method handles null argument fine.
The second version does not.
The second version would only give NPE if you call List.size(null), for all non-null inputs, it should behave absolutely similarly.
Therefore, just add if (list == null) return 0; to your second version.
I really suggest that you declare size() a as member method:
public int size() {
return next == null ? 1 : next.size() + 1;
}
so you can call : new List(1, null).size();
That is because you call List.size(null). In the first version you checl for list==null, in the second you don't.
The answer was inspired by a previous comment.
It is actually possible to do this
List list = null;
LinkedList.size(list);
and therefore if the list is uninitialised null.next can be called.
In other words: my list has to have at least two elements (firstelement and null)!
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to write a recursive method to put a binary tree in-order into an arrays, the sheet I got from my University told me I should write the method inside of a nested class "node" and let the outerclass call that Method in a new Method.
but the recursive method has to have its basis, and I can't ask if ( node == null ) because I am already inside the Class Node.
and (this == null) also doesn't seem quite right.
Edit:
I think I got what you are trying to say and I understood it, kind of.
As you were asking I am giving you the part of the code I am referring to.
public class BinaryIntTree {
public static class Node {
int value;
Node leftChild;
Node rightChild;
public Node(int value) {
this.value = value;
}
/**
* Performs an in order traversal and writes the
* values of the tree into the array starting at
* the specified start index. When done, the
* method returns the updated start index that
* is incremented by the number of values written
* to the array.
*
* #param array The array to write to.
* #param startIndex The start index to write from.
* #return The updated start index that is incremented
* by the number of values written to the array.
*/
public int toArray(int[] array, int startIndex) {
return 0;
}
}
public int[] toIntArray() {
int[] result = new int[getNodeCount()];
if (result.length != 0) {
root.toArray(result, 0);
}
return result;
}
}
There was a bit more methods in it which I deleted to point out the part I am struggling with.
Usually I did normal in-order traversal in the Binarytree class but our Prof now wants us to do it inside the nested class and let it be called in the outer class like you can see here.
I also cant figure out how I am supposed to go deeper into the tree when I cant even put a leftChild or a rightChild inside of the methods parameter which is supposed to be recursive in the nested Class.
I am not supposed to change the parameter or make the method static.
I hope I could describe it well enough.
Each node in your tree is a different instance of the Node class. The Node class likely has two Node type fields for its left and right child. You want to be doing this null check on that left and right child, and not on the current node (since the current node this always exists).
I'm trying to create an iterator class that completes what I thought would be two simple methods but I am having issues I suppose creating the iterator. The line where I create the iterator is giving me a compile error saying "Iterator is abstract; cannot be instantiated". I am not too sure what that means, obviously I did something wrong though. Also I put the purpose of the methods above them, if you see anything wrong with them let me know. Thanks for any input!
import java.util.Iterator;
private class OrderedListIterator{
Iterator<E> it = new Iterator<E>();
//return true if iterator has more items
public boolean hasNext(){
boolean found = false;
if(it.hasNext == true)
found = true;
return found;
return found;
}
//return next item in the iterator
public E getNext(){
if(it.hasNext != false)
return it.next;
}
//prints out message
public void remove(){
System.out.println("Operation not supported");
}
}
The reason you are getting this error is because an iterator is an interface.
In the Java programming language, an interface is a reference type,
similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. Method
bodies exist only for default methods and static methods. Interfaces
cannot be instantiated—they can only be implemented by classes or
extended by other interfaces. Extension is discussed later in this
lesson.
From the Java docs https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
An interface contains the definition of the methods, not the implementation and is why you can't create or call interfaces or it's methods. The iterator interface has two methods; hasNext() and next(). Your code looks like you intend to implement the iterator interface.
private class OrderedListIterator implements Iterator<E>
In your hasNext and next methods, you need to iterate over your OrderedList depending on how you have implemented it.
Here is an example of an iterator for an ArrayList which I have previously created.
private class ArrayIterator implements Iterator<E> {
private int arrayIndex = 0;
/**
* Checks if the set has a next value.
*
* #return true if there is a next value, else false
*/
public boolean hasNext() {
//Checks that the index is within the size of the ArrayList
return arrayIndex < size;
}
/**
* Gets the next value in the iteration.
*
* #return
* The next value in the list
* #throws NoSuchElementException
* if there is no next element in the list
*/
public E next() throws NoSuchElementException {
if (arrayIndex == size) {
throw new NoSuchElementException();
}
//Checks the ArrayList's data at the current index
return data[arrayIndex++];
}
}
Your private class is able to access the fields from it's surrounding class. In my example, the iterator stores an index (like an internal cursor) in the array and checks the ArrayList's data at the current index. Each time the next method is called, the index is increased for the next time.
If your OrderedList class is like a LinkedList and has nodes, you would save a reference to the node and each time the next method is called you would return the node, then change the cursor to the next node.
This question already has answers here:
Java iterator over an empty collection of a parameterized type
(7 answers)
Closed 8 years ago.
Can anyone let me know what is the real time use of an Empty Iterator in java? I'm curious to know why is it needed?
things like,
1. public static <T> Iterator<T> emptyIterator()
2. public static <T> ListIterator<T> emptyListIterator()
3. public static final <T> Set<T> emptySet(), etc..
source: http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyIterator()
You can use an empty iterator in cases where an API that you implement requires an iterator, but some of your code's logic can yield no items in the result. In that case, instead of returning a null, you return an empty iterator. You can also use an empty iterator to save some memory and for testing purposes.
Here is some example code that prevents returning null and saves some memory at the same time:
class LazyObjectInitialization {
private Collection<String> items;
public final Iterator<String> items() {
if(items == null || items.isEmpty()) {
return Collections.emptyIterator();
}
return items.iterator();
}
public final add(String item) {
if(items == null) {
items = new ArrayList<>();
}
items.add(item);
}
}
In the above class, the field items is not initialized until an element is added. So to provide expected behavior in method items() we return an empty iterator. The benefit from this are as follow:
Smaller memory consumption
The class allocates memory only when it is really needed.
Smaller memory mutation
Until we add something to the object, we never create a new instance of the iterator.
We never return null.
So my program has a need of a type of circular ArrayList.
Only circular thing about it has to be the get(int index) method, this is the original:
/**
* Returns the element at the specified position in this list.
*
* #param index index of the element to return
* #return the element at the specified position in this list
* #throws IndexOutOfBoundsException {#inheritDoc}
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
If index is -1 it should get the element with index ArrayList.size()-1 and if index is ArrayList.size(), it should get the element with index 0.
Simplest way of achieveing this which came to my mind is simply extending ArrayList from the java.util package and just overriding the get(int index) so it does not throw IndexOutOfBoundsException for the two indexes above, but change them to what I want. It would throw IndexOutOfBoundsException for any other index that is out of bounds.
However, since elementData(index) access a
private transient Object[] elementData;
I cannot make it work, because my class doesn't see it since it's private.
Also, I don't want to use any external libraries for this, simply because I think there are none that suit my needs, since I don't want a real circularArray, but only a part of it's functionality, rest of it being of the regular ArrayList.
So I have two questions:
How can I make this work? Is there a way to do it without copying the whole ArrayList class along with AbstractCollection, Collection and Iterable into my program? That seems like bad design even to me.
If I can somehow make it work, is there anything else I should watch for? If I make the changes described above, would that change the behaviour of the class only the way I want it to, or could there be any other undesired behaviour changes?
EDIT:
Thanks for the answer, here's what I've done:
import java.util.ArrayList;
public class CircularArrayList<E> extends ArrayList<E>
{
private static final long serialVersionUID = 1L;
public E get(int index)
{
if (index == -1)
{
index = size()-1;
}
else if (index == size())
{
index = 0;
}
return super.get(index);
}
}
It will wrap around the ArrayList, but only by one. I want it to throw an exception if I try to access any other element but the first and the last with anything except their regular ArrayList indexes.
You can extend the ArrayList class to change the functionality of the get method, without the need to access the elementData field:
public class CircularList<E> extends ArrayList<E> {
#Override
public E get(int index) {
return super.get(index % size());
}
}
The super.get method will still perform the range checks (but those will never fail).
You should be aware that doing this can give the ArrayList unstable indices. If the size of the list changes, then all indices outside of the normal range will change. For instance, if you have a list ['a','b','c','d','e'], then get(7) will return c. If you then do add('f'), then get(7) will suddenly return b, because get will now be working modulo 6 instead of modulo 5.
Can't you derive from ArrayList and override the the get(int index) method along those lines:
#Override
public E get(int index)
{
if(index < 0)
index = index + size();
return super.get(index);
}
What am I missing?
Note that this implementation would not fold arbitrary indices into your valid index range but only allow you to properly address your list from both the left and right sides (with positive and negative indices respectively, a bit like in Python).
What you described is basically getting the modulus of the index you want, and accessing that element in a list.
You could do the following with composition over inheritance:
Create a wrapper class for the interface List<T>, let's call it ListWrapper now
add a constructor accepting instance of List
let the List instance be protected, and name it to wrapped
Extend the wrapper class
Why do all this crap? This is implementation agnostic. One day, you might want to use this convenience on another implementation. Then you'll have to duplicate code, and hell begins. If you need a 3rd implementation too, and then add just one tiny bit of new functionality, you are doomed.
With a wrapper class in between:
you can have all classes implementing the List interface to have your own functinality
you'll be able to change the wrapper class in one place
you'll be able to add new functionality in one place.
Remember, we are writing programs that will have to be maintainable!
Wrapper class
public abstract class ListWrapper<T> implements List<T> {
protected final List<T> wrapped;
public ListWrapper(List<T> wrapped) {
this.wrapped = wrapped;
}
public T get(int index) {
return wrapped.get(index);
}
//omitting the other wrapper methods, for sake of brevity.
//Note: you still have to add them.
// Eclipse: Source menu, Generate Delegate methods does the trick nicely
}
Now the real new class
public class ModList<T> extends ListWrapper<T> {
public ModList(List<T> list) {
super(list);
}
#Override
public T get(int index) {
int listSize = wrapped.size();
int indexToGet = index % listSize;
//this might happen to be negative
indexToGet = (indexToGet < 0) ? indexToGet+listSize : indexToGet;
return wrapped.get(indexToGet);
}
}
BEWARE
this however is not safe for multithreaded environments!
be careful about all the instances of the original list - if you mutate that, the ModList instance will mutate too
The chosen answer doesn't handle the case where the index is a negative number with a very large magnitude and the size of the list is small i.e.
Size => 10
Index => -1000000
Here is an implementation that should handle all sizes and indexes
import java.util.ArrayList;
import java.util.Collection;
/**
* A list the loops round to the first element when {#link CircularList#get(int)} is called with an
* index that is greater than the max index of the list and vice versa.
*
* #author Stuart Clark
*/
public class CircularList<E> extends ArrayList<E> {
public CircularList() {
super();
}
public CircularList(int initialCapacity) {
super(initialCapacity);
}
public CircularList(Collection<? extends E> c) {
super(c);
}
#Override
public E get(int index) {
if (isEmpty()) {
throw new IndexOutOfBoundsException("The list is empty");
}
while (index < 0) {
index = size() + index;
}
return super.get(index % size());
}
}
Does anyone know this AbstractList extension : com.sun.appserv.management.util.misc.CircularList<T>. Take a look at it. It's GlassFish java.net community solution. It should be powerful because it's used in Thread Scheduling inside GlassFish Container.
I'm familiar with the ways I can get an element position in array, especially the ones showed here: Element position in array
But my problem is I can't figure out how to convert this code to fit my needs.
What I want to check is if a String has a match in an ArrayList and if so, what's the index of the String in the ArrayList.
The annoying part is I managed to verify the String is in the ArrayList (see first line of my code)
listPackages is the ArrayList
current_package is the String I want to find its position in listPackages.
Here's my code:
if (listPackages.contains(current_package)) {
int position = -1;
for(int j = 0; j < listPackages.size(); j++) {
if(listPackages[j] == current_package) {
position = j;
break;
}
}
}
Would appreciate any help!
Thanks!
Use indexOf:
int index = listPackages.indexOf(current_package);
Note that you shouldn't generally use == to compare strings - that will compare references, i.e. whether the two values are references to the same object, rather than to equal strings. Instead, you should call equals(). That's probably what was going wrong with your existing code, but obviously using indexOf is a lot simpler.
just use the call listPackages.indexOf(current_package);
ArrayList.contains(Object o) calls indexOf(Object o) internally in ArrayList:
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* #param o element whose presence in this list is to be tested
* #return <tt>true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
Hope this will help you.change your code like this:
if (listPackages.contains(current_package)){
int position=listPackages.indexOf(current_package);
}
Also if you will make position variable as global you can access its value outside this block of code. :)
use the indexof method to get the position -
listPackages.indexOf(current_package)
http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)