Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Store multiple objects in a single array
06-25-2008, 06:13 PM
Post: #1
Question Store multiple objects in a single array
Pls let me know how I can store multiple objects in a single array. If possible kindly give me a code snippet to show how it is done.
Find all posts by this user
Quote this message in a reply
06-25-2008, 06:51 PM
Post: #2
RE: Store multiple objects in a single array
[java]
public class ArrayTest {
public static void main(String[] args) {
Object objArray[] = new Object[2];
String strObj="Hello World";
Integer intObj = new Integer(10);

objArray[0] = strObj;
objArray[1] = intObj;

for (int i = 0; i < objArray.length; i++) {
System.out.println(objArray[i]);
}
}
}
[/java]

Is this what you want? Here I am storing an object of string and Integer to a single array
Visit this user's website Find all posts by this user
Quote this message in a reply
06-25-2008, 07:05 PM
Post: #3
RE: Store multiple objects in a single array
Thanks Albin this is what i wanted. Thanks a lot. Also one more thing: If I have a prog like this:

class A{
A()
{
System.out.println("in A");
}

public void disp()
{
System.out.println("Hi");
}
}
class B{
B()
{
System.out.println("in B");
}

public void display()
{
System.out.println("Hello");
}
}
class Test{
public static void main(String args[])
{
Object arr[]=new Object[5];
arr[0]=new A();
arr[1]=new B();
arr[2]=new A();
arr[3]=new B();
arr[4]=new A();
arr[0].disp();
}

Is this correct? kindly let me know if there are any problems with this code.
Find all posts by this user
Quote this message in a reply
06-25-2008, 07:12 PM
Post: #4
RE: Store multiple objects in a single array
Everything except this line arr[0].disp(); is fine. This would give a compile time error as you don't have any method named disp in Object class. So before calling the disp() method cast arra[0] to an an object of A. So it should be something like

[java]
((A)arr[0]).disp();
[/java]
Visit this user's website Find all posts by this user
Quote this message in a reply
06-25-2008, 07:24 PM
Post: #5
Smile RE: Store multiple objects in a single array
Great. Now its working perfectly fine. Thank you so much Albin.
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump: