views:

200

answers:

5

I am working on learning java a little, and i found this question in a java text book on Google books, I have been working on it for a while, and for some reason these seems like it should be simple. Anyone bored and would like to show me what this is suppose to look like in Java code??

(Using ArrayList) Write a program that creates an ArrayList, adds a Loan
object, a Date object, a string, a JFrame object, and a Circle object to the list,
and uses a loop to display all the elements in the list by invoking the object’s
toString() method.
+1  A: 
List<Object> list= new ArrayList<Object>();
list.add("A String");
list.add(new JFrame());
list.add(new YourCircleObject());
(...)
for(Object o:list)
 {
 System.out.println(o.toString());
 }
Pierre
thanks for your help also
Madison
+3  A: 

This code assumes that the various objects in question have no-parameter constructors. Else just stick the parameters in appropriately:

ArrayList<Object> list = new ArrayList<Object>();
list.add(new Loan());
list.add(new Date());
list.add(new String());
list.add(new JFrame());
list.ad(new Circle());

for (Object obj : list)
{
    System.out.println(obj.toString());
}
bguiz
thanks for your input
Madison
+1  A: 

Without giving you the exact code (you are trying to learn Java, right?) the goal of the exercise is to show you that every type of object in Java extends from the root base class Object. There are certain things that you can do on any instance of Object, no matter what it's concrete implementation (such as toString() for instance).

Additionally the exercise is also teaching you about the Collections API and how you can build collections of heterogeneous objects. Spend a little time looking at the Collections API documentation.

BryanD
well i dont have a teach to show me examples and what not.. so i will take what i see here and try to apply to other circumstances. thats how i learn
Madison
A: 

Well, the Loan and Circle classes don't exist in the Java library, you'll have to define your own. All the others live in various packages such as java.util or javax.swing. If Eclipse didn't automatically do the imports for me, I'd use Google to find the package names I need for the import statements.

That done, you can instantiate all of them using new. First you create an ArrayList, then you do something like

myList.add(new JFrame())

to add those other objects to the list.

Then you use a for loop to run through the list and output the elements using System.out.println.

Carl Smotricz
A: 

import java.util.*;

public class Exercise9_6 { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add(new Loan()); list.add(new Date()); list.add(new javax.swing.JFrame());

for (int i = 0; i < list.size(); i++)
  System.out.println(list.get(i));

} }

HuiEe