I've been programming for quite a bit now, but I have a problem. What I am trying to do is implement a class which has the same capabilities as a built-in data type int[].
The following methods were provided for me:
public ArrayOfInt(int size);
public int length();
public int get(int index);
public void put(int index, int value);
The main method is for testing the code.
I pretty much have no idea where to start. Can somebody help me?
Edit: Here's my updated code. When I try to use d.put(0,1), I get a nullpointerexception error, which is what I'm now confused about. Shouldn't d.put(0,1) define the index and value integers?
public class ArrayofIntegers
{
private int[] arr;
public int ArrayOfInt(int size)
{
arr = new int[size];
return size;
}
public int length()
{
return arr.length;
}
public int get(int index)
{
return arr[index];
}
public void put(int index, int value)
{
arr[index]=value;
System.out.print(arr[index]=value);
}
public static void main(String[] args)
{
ArrayofIntegers d = new ArrayofIntegers();
d.put(0,1);
}
}
I think that you shouldn't reinvent the wheel since java has some built in modifiable alternatives to an array like a List. List is generic so you can create a List of Integers like this:
List<Integer> intList = new ArrayList<Integer>(); // can be ArrayList<> in java 1.7
and enjoy the benefits of the List interface. If the built-in implementations (like LinkedList and ArrayList) are not good enough for you then you can always extend the AbstractList which is provided in the Java Collections Framework.
If you need more help check out the official documentation: Java List
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With