I come from a PHP background and I’m just getting my teeth into some Java. I was wondering how I could implement the following in Java as simply as possible, just echoing the results to a terminal via the usual “System.out.print()” method.
<?php
$Results[0]['title'] = "No Country for Old Men";
$Results[0]['run_time'] = "122 mins";
$Results[0]['cert'] = "15";
$Results[1]['title'] = "Old School";
$Results[1]['run_time'] = "88 mins";
$Results[1]['cert'] = "18";
// Will basically show the above in order.
foreach($Results as value) {
echo $Results[$value]['title'];
echo $Results[$value]['run_time'];
echo $Results[$value]['cert'];
}
// Lets add some more as I need to do this in Java too
$Results[2]['title'] = "Saving Private Ryan";
$Results[2]['run_time'] = "153 mins";
$Results[2]['cert'] = "15";
// Lets remove the first one as an example of another need
$Results[0] = null;
?>
I hear there are “list iterators” or something that are really good for rolling through data like this. Perhaps it could be implemented with that?
A fully working .java file would be most handy in this instance, including how to add and remove items from the array like the above.
P.S. I do plan on using this for an Android App in the distant future, so, hopefully it should all work on Android fine too, although, I imagine this sort of thing works on anything Java related :).
If I were doing that in Java I would make the following changes:
Movieclass that encapsulates the data about a movieLists instead of native arraysA
Movieclass may look something like this:Then you could make a List of Movies like so:
You can remove Movies like so:
And you can iterate through them like so:
If you wanna get specific things out of the List, you can do the following:
To view an entire
Listsimply do:Note: This assumes that the
Movieclass has an intelegenttoString()method written for it.For some more reference on
Lists that I showed above, check out the javadocs on them.When writing in a OO language, you should use OO principles.
It may also be helpful to read this question and my answer to it. It is very similar in that you two are both trying to do things with arrays that would better be served using classes.