I'm new to Java and used to create arrays and objects in PHP.
Now I wrote a short function in Java for extractions some parts of the text. The function packs up all extracted text pieces into an object and returns to the main code. However whatever I do with the returned result I can't get items back from that.
Here is my code:
public void main(String text) {
Object[] entities = (Object[])extractNamedEntities(text);
Object names = entities[0];
Object locations = entities[1];
Object orgs = entities[2];
for (Sting name : names) {
System.out.println(name);
}
}
private static Object extractNamedEntities(String text) {
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> locations = new ArrayList<String>();
ArrayList<String> orgs = new ArrayList<String>();
// Then processing the text and then...
names.add("Name1");
names.add("Name2");
locations.add("Loc1");
locations.add("Loc2");
orgs.add("Org1");
return new Object[]{names, locations, orgs};
}
I get the following error:
Compilation failure for-each not applicable to expression type required: array or java.lang.Iterable found: java.lang.Object
namesis just a singleObject- you cannot iterate it because there is only 1. If you want to handle it as aListyou need to cast it to aList.Object names = entities[0];You had to do that because your method is returning anObject[]instead of a List of Lists. Basically, why did you do thisreturn new Object[]{names, locations, orgs};? MakingObjectis throwing away all the useful stuff about the lists you just made.Object names = ...isObject. Because compiler doesn't have any guarantee that value of that variable will always be some kind of iterable object holding strings (sinceObjecttype variable can also hold any other type, like Integer, String, Person, etc...) it will not allow us to create code which potentially will try to iterate some non-iterable object since that would break type-safety which is one of main reasons we use Java.ArrayList<String>likeArrayList<String> names = (ArrayList<String>)entities[0];which will make type ofnamesvariableArrayList<String>. OR don't declare yourextractNamedEntitiesmethod to return anObject. Since it will always return group of ArrayLists of Strings you can declare that it returns something likeList<ArrayList<String>>andreturn Arrays.asList(names, names, locations, orgs);.