tastyminerals
tastyminerals

Reputation: 6548

Why I can't add an Object to an Object[] array?

I know I can use ArrayList for this, but I don't understand why I can't add an Object intance to the following Object[] array?

class Penguin {
    public void say(){
        System.out.println("Hi, I am a penguin!");
    }
}
public class TempTest {
    private Object[] items;
    private int next = 0;
    private int i = 0;
    public void add(Object x){
        if(next < items.length)
            items[next++] = x;
    }
    public boolean end() { return i == items.length; }
    public Object current() { return items[i]; }
    public void next() { if(i < items.length) i++; }

    public static void main(String[] args) {
        Object[] obj = new Object[5];
        Object p = new Penguin();
        obj.add(p);
    }
}

Eclipse screenshot

Upvotes: 0

Views: 1207

Answers (6)

ARUN
ARUN

Reputation: 11

You need to mention object array index there instead of add method .

obj [array index] = p ;

Upvotes: 0

Rakesh KR
Rakesh KR

Reputation: 6527

obj is an array, you can add elements by

obj[0] = object1;

Upvotes: 1

newuser
newuser

Reputation: 8466

Assign value for an array

obj[0] = p;

instead of

obj.add(p);

Upvotes: 1

Maroun
Maroun

Reputation: 95978

Because obj is an array, you simply add elements by indexes:

obj[0] = someObject;

In your case, you should add elements using a loop, from 0 to 4.

See Arrays for more information.

Upvotes: 3

Rogue
Rogue

Reputation: 11483

Arrays don't have an add function, you're thinking of Collections.

When you have an array of a specific size, you can set the indexes of that array:

Object[] arr = new Object[2];
arr[0] = /* your object */;

//...
Object yourObj = arr[0]; //returns that object

As pointed out by @SubhrajyotiMajumder , try calling your class' local implementation of the method:

this.add(yourObj);

And from there potentially refactor code so that you are editing the same array each time, not one that you made locally.

Upvotes: 3

Juned Ahsan
Juned Ahsan

Reputation: 68715

Object class does not have any method called add. Its an array so u need to put objects using index.

Also creating an array of Object is not a good idea unless u really have a real need of doing so. Better use collections.

Upvotes: 2

Related Questions