|
Store multiple objects in a single array
|
|
06-25-2008, 06:13 PM
Post: #1
|
|||
|
|||
|
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.
|
|||
|
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 |
|||
|
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. |
|||
|
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] |
|||
|
06-25-2008, 07:24 PM
Post: #5
|
|||
|
|||
|
Great. Now its working perfectly fine. Thank you so much Albin.
|
|||
|
« Next Oldest | Next Newest »
|

Search
Member List
Calendar
Help




