Erebus
Erebus

Reputation: 53

Understanding The Idea of Objects In An Array

Could give me a concrete explanation of putting objects in an array?

I know you can put numbers in an array and then manipulate, sort, or perform other functions with these numbers. However, I have a hard time understanding how you're able to do this with objects in an array.

Correct me if I'm wrong, but seems that an object is like a class and a class is a blueprint. So, when you put different objects in an array, aren't you putting different "blueprints" in the same array? How does that work? What is the usefulness of doing this?

Or can you only put objects from the same class in one array and not objects from different classes in the same array?

Upvotes: 3

Views: 118

Answers (3)

Nathan Hughes
Nathan Hughes

Reputation: 96385

A class is a template for creating objects. The class is a certain type of object (an object of type String is created using a class called java.lang.String.class). You can find the class of an object by calling getClass() on the object. The class is separate from the object that it was used to create.

An array of objects has references to the objects. The objects exist somewhere in memory, the array has pointers to them. When the array is sorted the code follows the references to find the data in the objects, then reassigns the references to different array elements.

Also, if you have an array of Object (Object[]), you can put objects of any class in it.

Upvotes: 1

venki
venki

Reputation: 1131

In java everything is an Object [Except primitives - int, float etc]. Even Array is an object.

We dont put Objects into the array. We store object references in an array. Your Object lives on a heap, and its reference will be on a stack.

While declaring array, we declare what type of object it is. If I declare the array as an object of type MyClass,

MyClass[] arr = new MyClass[10]; 

then I can store all the objects of MyClass and objects of sub-classes of MyClass in my array. You cannont store any other objects, we will get a compilation error.

However, if we declare the array as type Object,

Object[] obj = new Object[5];

Then we can insert any object refernece in our array.

Why do we use objects in arrays?

Suppose I have three objects of MyClass and I want to pass these from my Java to corresponding JSP. I can do it by creating an array and storing all the three objects in it and then we will pass the array to Jsp.

Upvotes: 0

oliver
oliver

Reputation: 83

Under normal circumstances, it put only one type of object to an array. You can use arrayList limit type.

Upvotes: 0

Related Questions