-1

I want to add an object to my array. I am trying to create a method so whenever it's called, it adds the generic type object. Here's my code:

public class ArrayObjects<E> implements SomeImp<E>{

    private E[] list;

    private int maxCapacity, currentSize;

    public ArrayObjects(){
        maxCapacity = 10;
        array = (E[]) new Object[maxCapacity];
    }

    public void addObj(E obj){
        array.add(obj); //Throws an error
    }
}

Eclipse shows me an error though. It says "Cannot invoke add(E) on the array type E[ ]"

Does anyone know why does this happen? Do you know of an alternative of adding an object to my generic array?

Thank you!


EDIT:

When I create an instance of a class that instantiates ArrayObjects, and try to add a value to it, it doesn't do it. code:

import packageWhereArrayObjectsIs.*;


public class Test {
    private ArrayObjects<Integer> list;

    public Test() {
        list = new ArrayObjects<Integer>();    
        Test();
        }

    private void TestOne() { 
        for(int i=1; i <= 10; i++)
            list.addLast(i);         
        System.out.println("Should print 1 .. 10");
        System.out.println(list);

    }
}
Cesar A
  • 663
  • 1
  • 7
  • 10

2 Answers2

1

The method add() does not exist for arrays. You must access array elements using the correct syntax []:

    public void addLast(E obj) {
        array[currentSize++] = obj;
    }

In order for your list to print nicely, you'll want to add a toString() method to your ArrayObjects class:

    public String toString() {
        return Arrays.toString(array);
    }

To iterate over the elements of your ArrayObjects, you can implement the Iterable interface:

public class ArrayObjects<E> implements Iterable<E>

This requires your class to have an iterator() method that returns an Iterator:

    public Iterator<E> iterator() {
        class It implements Iterator<E>
        {
            int position = -1;
            public boolean hasNext() {
                return position + 1 < currentSize;
            }
            public E next() {
                return array[++position];
            }
            public void remove() {
                throw new UnsupportedOperationException();
            }
        }
        return new It();
    }

Finally, this code shows how you can now iterate over your list using an enhanced for loop:

        ArrayObjects<Integer> list = new ArrayObjects<Integer>();
        for (int i = 0; i < 10; i++) list.addLast(i);
        for (Integer i: list) {
            System.out.println("Iterating over list! Next element is " + i);
        }
gknicker
  • 5,509
  • 2
  • 25
  • 41
  • It worked! It got rid of the error, but now that I try to use my class in my edit (see my edit above), the only thing that prints is "packageWhereArrayObjectsIs.ArrayObjects@3343c8b3" – Cesar A Feb 19 '15 at 03:58
  • @CesarA This means that you need to override the toString method of your class. Since you didn't do that, a generic toString method is called which is derived from the Object class and that will just give you a gist of what the string representation could look like – smac89 Feb 19 '15 at 04:03
  • @CesarA I added a `toString()` example to my answer; that will help you print your class nicely :) – gknicker Feb 19 '15 at 05:12
  • Thank you for your response. In the case I wanted to use an Iterator, how would I implement it to iterate through the array? Your help is much appreciated! – Cesar A Feb 19 '15 at 05:38
  • @CesarA I updated my answer to show you how to iterate through the array. Don't expect me to help you any more though, since you chose someone else's answer. – gknicker Feb 19 '15 at 06:26
0

You should do something like this, assuming that your actual size is 1 when you add your first element BUT the position will be 0 because it's the first position of the array.

public boolean addObj(E obj){

    if(actualSize == maxCapacity){
        return false;
    }

    array[actualSize--] = obj;

    return true;
}

I changed the return value to return false if there is no positions left in the array (considering that you won't remove any object in the middle).

Why do you need an array? Why not going with a List?

public class ArrayObjects<E> implements SomeImp<E>{

private List<E> list;

private int maxCapacity;

public ArrayObjects(){
    maxCapacity = 10;
    list = new ArrayList<E>();
}

public boolean addObj(E obj){

    if(list.size() == maxCapacity){
        return false;
    }

    list.add(obj);

    return true;
}
}

See that using a List you won't have to deal with the actualSize.

EDIT: as Smac89 points out, it makes no sense to use a list. But keep in mind you will have to find an empty position if the array is not full.

Luke SpringWalker
  • 1,600
  • 3
  • 19
  • 33
  • Seems redundant to use a list in a class that is acting as a list. Why not just use the list directly without the unnecessary encapsulation. Also note that the first one could end up not inserting any elements or cause an index exception – smac89 Feb 19 '15 at 04:06
  • @Smac89 how could it limit the number of entries to the list without encapsulation? – Luke SpringWalker Feb 19 '15 at 04:11
  • If a limit is required, List is still not the solution an array will be a better option. So your initial solution will work there – smac89 Feb 19 '15 at 04:14
  • Please see my edits above. Modified my code. It still complains about "cannot invoke add(E) on the array type E[ ] " – Cesar A Feb 19 '15 at 04:16
  • @CesarA add() is a List method, when you are using arrays you have to make explicit the position you want to use. Try my first solution. – Luke SpringWalker Feb 19 '15 at 04:20
  • Yes. But what if I wanted to use the list alternative, how would I do it? Im more interested in the list way because then I can use add() remove() etc.. Thanks for your further help! – Cesar A Feb 19 '15 at 04:25
  • I know it's easier to handle with a list, the code I written above (second example, check that I also changed the properties of the class) should work. But for better practises consider what Smac89 says. If you are willing to add another library to the project, take a look at this post: http://stackoverflow.com/questions/5207162/fixed-size-list-in-java – Luke SpringWalker Feb 19 '15 at 04:30