开发者

Get Items Feeds4J Java Array

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?


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


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>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜