[java] Simple array with generics?

Started by
4 comments, last by Fenrisulvur 14 years ago
Hey dudes! I understand how to use generics when you use a generic array, but i still havent found much about how to use a simple array with generics. Anyone got a link to a tutorial or would like to explain? would be real helpful :D
Advertisement
Can you explain more, perhaps with code? I'm not sure what distinction you are getting between a "generic array" and an "array with generics".
By any chance do you mean the arrayList collection class when you said array the first time?
Hello!

The code is:
import java.util.Arrays;

public class ObjectArrayList
{
private Object[] listArray = new Object[1];
private int lastIndex = 0;

/**
* Method for adding a new object at the last place of the list.
*
* @param o The object to be inserted.
*
*/

public void addLast(Object o)
{
if (lastIndex + 1 >= listArray.length)
expandArray();

listArray[lastIndex++] = o;
}

/**
* Method for adding a new object on the first index.
* The method is using the insert-method for achieving this.
* @param o The Object to be inserted into the list.
* @throws IndexOutOfBoundsException if the supplied
* index is greater than the size of the list.
*
*/

public void addFirst(Object o)
{
insert(o, 0);
}

/**
* Method for inserting a new object at a given index.
* Expands the internal array if neccesary.
*
* @param o The Object to be inserted into the list.
* @param index The index where the Object is going to
* be inserted.
* @throws IndexOutOfBoundsException if the supplied
* index is greater than the size of the list.
*
*/

public void insert(Object o, int index)
{
if (index < 0 || index > lastIndex)
throw new IndexOutOfBoundsException();

if (lastIndex + 1 >= listArray.length)
expandArray();

for (int i = lastIndex; i >= index; i--)
listArray = listArray<span style="font-weight:bold;">;<br> <br> listArray[index] = o;<br> lastIndex++;<br> }<br> <br> /**<br> * Method for retrieving an element at a given index.<br> *<br> * @param index the index of the element to retrieve.<br> * @throws IndexOutOfBoundsException if the given index is<br> * less than zero or larger than the size of the array.<br> * @return Object the selected object.<br> *<br> */<br> <br> public Object get(int index)<br> {<br> if (index &lt; 0 || index &gt;= lastIndex)<br> throw new IndexOutOfBoundsException();<br> <br> return listArray[index];<br> }<br> <br> /**<br> * Method for sorting the array, using the Arrays.sort()-method.<br> * The method sorts the objects in the interval between zero and <br> * lastIndex to avoid NullPointerExceptions.<br> *<br> */<br> <br> public void sort()<br> {<br> Arrays.sort(listArray, 0, lastIndex);<br> }<br> <br> /**<br> * Method for removing an element at a given index. <br> *<br> * @param index the index of the element to remove.<br> * @throws IndexOutOfBoundsException if the given index is <br> * less than zero or larger than the size of the array.<br> * <br> */<br> public void delete(int index)<br> {<br> if (index &lt; 0 || index &gt;= lastIndex)<br> throw new IndexOutOfBoundsException();<br> <br> for (int i = index; i &lt; lastIndex; i++)<br> listArray<span style="font-weight:bold;"> = listArray;<br> lastIndex–;<br> <br> }<br> <br> private void expandArray()<br> {<br> Object[] newArray = new Object[listArray.length*2];<br> for (int i = 0; i &lt; listArray.length; i++)<br> newArray<span style="font-weight:bold;"> = listArray<span style="font-weight:bold;">;<br> <br> listArray = newArray;<br> }<br> <br> /**<br> * Method for retreiving a textual representation of the list.<br> *<br> * @return String The textual representation of the list.<br> *<br> */<br> <br> public String toString() <br> {<br> String result = "[";<br> for (int i = 0; i &lt; lastIndex; i++)<br> {<br> result += listArray<span style="font-weight:bold;">;<br> <br> if (i &lt; lastIndex - 1)<br> result += ", ";<br> }<br> <br> result += "]";<br> <br> return result;<br> }<br> <br> /**<br> * Method for retreiving the size of the list, using the lastIndex variable<br> *<br> * @return int The number of elements in the list.<br> */<br> <br> public int size()<br> {<br> return lastIndex;<br> }<br>}<br><br>thx for the fast awnser guys:D<br><br>Edit: My assignment is to make the list generic without changing the array. If i could change the array it wouldnt be that hard but now that i cant i´m stuck..<br><br>thanks again:)
You should research how generics are implemented in Java. A simple overview is that it is done with type erasure, the compiler verifies that the code is type safe, then it replaces the code with similar code that deals with Object instances, and inserts casts where appropriate.

Another interesting idea is that you cannot implement this class using a "generic array", because you cannot allocate an array of generic type in Java. This is because of how arrays are implemented. You can assign an array of type Foo to any supertype of Foo. However, this introduces a potential for error:
public static void example(){	String [] strings = new String[1];	Object [] objects = strings;	objects[0] = new Integer(1);}

This will compile, but if you try run it it will throw an ArrayStoreException. This is because the types stored in the array must be Strings, so even though we can read the elements in the "objects" array, we cannot write non-strings into this array. Consider the following illegal java code:
public static <T> void example(){	T [] generic = new T[1];	Object [] objects = generic;	objects[0] = new String();	objects[0] = new Integer(1);}

If this were to compile, at runtime the T type would be erased, and this would result in the type of "generic" to be Object[], which means that the array no longer can throw the ArrayStoreException when a non-T type is written to it.

In summary, the type ArrayList in Java is actually implemented much the same way as your code is going to be. What you need to think about is the invariants your class will impose. For example, if you only ever write T instances into the array, even though the array is of type object then it is safe to cast any element of the array to type T.
Quote:Original post by rip-off
This will compile, but if you try run it it will throw an ArrayStoreException.

This, btw, is one of my least-favoured "features" of Java, and I'd strip it from the JLS given the chance. Do not rely on it in your code.

This topic is closed to new replies.

Advertisement