Java Class (C++ Structure Like) Help
Hi, I am creating a class that is like a (struct in c++),
Code :
class MyStructTest
{
public String var1, var2, var3;
public MyStructTest(String var1, var2, var3) {
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;
}
}
then i make an arraylist of the type MyStruct
Code :
public ArrayList<MyStructTest> myList = new ArrayList<MyStructTest>();
i want to be able to add items to the arraylist by being able to choose which String of the struct like
myList . element1 . var1 = "something"; and so on
and then being able to access like myList element 1's var1.
how would i add things to the arraylist and access each part of each element as such.
Thanks
}
Re: Java Class (C++ Structure Like) Help
Quote:
i want to be able to add items to the arraylist
Read the API doc for the ArrayList class to see what methods it has for adding items to it.
Quote:
access like myList element 1's var1.
Again see the ArrayList API doc for methods that access the contents of the array list.
Once you get a class object reference from the ArrayList, you can use that reference to get to its contents like var1.
Re: Java Class (C++ Structure Like) Help
Lists are based upon index...if you wish to be able to grab an object based upon a value, perhaps a Map might be more appropriate?
(see The Map Interface (The Java™ Tutorials > Collections > Interfaces) )
Re: Java Class (C++ Structure Like) Help
Hi, I figured out what i was doing wrong.
I had to create an object of the type MyStructTest, and then set its attributes. and then add that to the arraylist.
Thanks.
Re: Java Class (C++ Structure Like) Help
I have a different problem, with the arraylist.
I call a method from another class and add an element to that arraylist, if i print out the contents of the arraylist from within the method that added something to it, the arraylist contents are shown.
But if i later call a method that is meant to show the contents, it says the arraylist is empty
I dont understand why?
thanks
Re: Java Class (C++ Structure Like) Help
Make sure that there is only one arraylist with a specific name. If you have two with the same name there will be confusion. You will add something to one and then later look in the other one and it will be empty.
Re: Java Class (C++ Structure Like) Help
Hi, thanks, what you said made me realise what I was doing wrong =).
What i was doing wrong was that I was making a reference to the other class multiple times in each part.
e.g Something somethingRef = new Something();
I made only one reference at the top of the code and now it all works perfectly.
thank you =)