views:

78

answers:

2

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 :).

+2  A: 

You can first create a class defining the Data Structure and then build an ArrayList of these object to actually store values. ArrayList is one of many Collection available in Java and provides many methods to iterate over them and add or delete items.

For e.g.: your class could look like:

class Movie{

String title;
String run_time;
String cert;
...//getter,setter methods for these instance variables/fields
}

// you then create movie objects and populate some data in them
Movie one = new Movie();

one.setTitle("No Country for..");
one.setRunTime("122 mins");
one.setCert("15");

//create arrayList to store movie objects
ArrayList<Movie> list = new ArrayList<Movie>();

//add item to list
list.add(one);

// iterate over arrayList to get values
for(Movie item:list){
System.out.println(item.getTitle());
}

Reference: ArrayList

Samuh
Good answer. Heh, great minds think a like.
jjnguy
+4  A: 

If I were doing that in Java I would make the following changes:

  1. Make a Movie class that encapsulates the data about a movie
  2. Use Lists instead of native arrays

A Movie class may look something like this:

public class Movie {

    public final String title;
    public final int runtime;
    public final int cert;

    public Movie(String title, int runtime, int cert) {
        this.title = title;
        this.runtime = runtime;
        this,cert = cert;
    }
}

Then you could make a List of Movies like so:

List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie("Some Movie", 120, 15);
movies.add(new Movie("Another Movie", 90, 18);

You can remove Movies like so:

movies.remove(0);

And you can iterate through them like so:

for (Movie m: movies) {
    System.out.println("Title: " + m.title + 
                       ", Runtime: " + m.runtime + 
                       ", Cert: " + m.cert);
}

If you wanna get specific things out of the List, you can do the following:

Movie the2ndOne = movies.get(1);
System.out.println("Title: " + the2ndOne.title); // or
System.out.println("Title: " + movies.get(0).title);

To view an entire List simply do:

System.out.println(movies.toString());

Note: This assumes that the Movie class has an intelegent toString() 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.

jjnguy
@Justin: you beat me by a minute! :)+1 because your code is complete
Samuh
@Samuh, ha. Actually you beat me by ~35 seconds.
jjnguy
This looks ace!! Thank-you very much for that!One final question though, can I still echo out specific things once they are inside the list??In PHP I would usually do something like:<?php// Picked random things hereecho $Results[1]['run_time']; // Echos "88mins"echo $Results[0]['title]; // Echos "No Country For Old Men"?>
Andy Barlow
Yup, I'm gonna edit my answer to add some more info. But in short use `list.get(index)` to get a specific element. @Andy
jjnguy
I have a final question about this. In PHP there is a Print_r function which shows me the entire array. Is there a similar method that would work so I can get a simple string of the entire list (including all added movies)?Otherwise, this works absolutely perfectly!!!
Andy Barlow
@Andy To do that you would need to override the `toString()` method of Movie. Create that method, then call `System.out.println(movies.toString())`
jjnguy
How to you mean by intelligent? Any change of an example or is it fairly complex??I assume something along the lines of:<code>@Override public String toString() { return this.studio;}</code
Andy Barlow
@Andy, it is not hard. You are very close to correct. `public String toString(){ return "Title: " + m.title + ", Runtime: " + m.runtime + ", Cert: " + m.cert; }`
jjnguy
@Andy, something like that will mat a Movie.toString() return a well formatted string. The List toString will then use that toString from Movie when it gets printed out.
jjnguy