Collection ... How to use collections of classes

I am working on making a lot of my utility apps run on linux
(trying to make the switch from windows)

well i have gotten so used to C# and .net that i wanted to find a comparable language that works on other OS's

after examining code examples it looks like java and c# are pretty similar. but I'm having trouble with a few oddities, in this case

what I am trying to accomplish is:
1) Create a class with a bunch of properties and methods ...
2) Create a collection of the above class
3) Get the value of any property or call methods from any class in the collection

1 & 2 i believe i have correct.
but 3 is where i am stumped

in C# i am used to doing 3 in this manner:

// 1) Class animal
public class animal{
public String Name;
public String Type;

public animal(String name, String type){
this.Name = name;
this.Type = type;

// 2) Create a collection of animals
Collection Animals = new Collection();

// Assign values
Animals.add(new animal("Bill", "Duck"));
Animals.add(new animal("Fred", "Dog"));
Animals.add(new animal("Jasmine", "Cat"));
Animals.add(new animal("Jannet", "Rhino"));

* problem is here *************
// 3) Use the data

String MyPetName = Animals[2].Name;
// C#: assigns the value of the 3rd element in the
// Collection of animals' Name property
// "Jasmine"

how would i do the above in java?
i cannot find a way to access the members of the objects inside the collection in java. I have searched tutorials and i couldn't find anything that made sense to me. none of the examples I found involved collections of classes.

any help would be grand :)

sorry for the long post


  • Answered my own question,

    or at least found a work around

    i just found out that
    [code]for( : ){}[/code]
    is a foreach() loop :) oh joy i was looking for this loop :D

    so by doing
    for(animal anml : Animals){
    somethingsomthing = anml.Name;

    and i just zip thru the collection that way

    hope this helps anyone else that was confused as well
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion