views:

66

answers:

2

Im from php, so i want to lear java. In php in a for loop if i want to create an array i just do

$items = $this->getItems();
for($i=0;$i<count($items);$i++)
{
 $myarrayitems[$i] = $items[$i];
}

return $myarrayitems;

But in java i got arrayoutofexponsion or like that.

here is the code im trying

public String[] getItems(String url) throws Exception
{
URL rss = new URL(url);
Feed feed = FeedParser.parse(rss);
int items = feed.getItemCount();
int a = 0;

for (int i = 0; i < items; i++) 
{
FeedItem item = feed.getItem(i);
String title[i] =  item.getTitle();
}

return title;

}

How can i return title as array an make an var_dump of that?

+1  A: 

You have to define title as an array before using using it:

String title = new String[ARRAY_DIMENSION];

If you don't know *ARRAY_DIMENSION* you could use this:

List<String> title = new ArrayList<String>();

or this, if you do not mind String order in the ArrayList:

Collection<String> title = new ArrayList<String>();
Alberto Zaccagni
but i dont know how big the array_dimension is so i cant insert an 10 or 20
streetparade
@streetparade: Yes you do, you've got it in the `items` variable, surely...
Jon Skeet
+1  A: 

You need to create the array with the right number of elements to start with. Something like this:

public String[] getItems(String url) throws Exception
{
    URL rss = new URL(url);
    Feed feed = FeedParser.parse(rss);
    int items = feed.getItemCount();
    // We know how many elements we need, so create the array
    String[] titles = new String[items];

    for (int i = 0; i < items; i++) 
    {
        titles[i] = feed.getItem(i).getTitle();
    }

    return titles;    
}

A potentially nicer alternative, however, is to return a List<String> instead of a string array. I don't know the FeedParser API, but if you can iterate over the items instead you could do something like:

public List<String> getItems(String url) throws Exception
{
    URL rss = new URL(url);
    Feed feed = FeedParser.parse(rss);
    List<String> titles = new ArrayList<String>();
    for (Item item : feed)
    {
        titles.add(item.getTitle());
    }    
    return titles;    
}

This will work even if you don't know how many items there are to start with. When Java eventually gets concise closures, you may well be able to express this even more simply, as you would in C# with LINQ :)

Jon Skeet
thanks Jon for the help.
streetparade