Reputation: 29
Let me know if I need to provide more code, but I am getting a syntax error for the last line in this snippet stating incompatible types; Object cannot be converted to String
. I can't figure out why this ArrayList
is considered to be made up of Object
s instead of String
s.
As you can tell, inputList
was passed down from a different method, and it gets a little complicated from here to just post snippets, but as far as I can tell, everywhere else these ArrayList
s are always defined as String
s.
Any input (see what I did there?) would be appreciated!
public static ArrayList<String> getURLsContainingTarget(ArrayList inputList, String target) throws MalformedURLException
{
ArrayList<String> outputList = new ArrayList<>();
String regEx;
regEx = "*" + target + "*";
String line= "null";// this is a line in the web page
// one loop to read through each URL in inputList
for (int i = 0; i < inputList.size() - 1; i++)
{
String URLline = inputList.get(i);
Upvotes: 2
Views: 175
Reputation: 8156
If you don't define type of ArrayList
then it ll considered as Object type so you have two option :
1 :
define inputList
as String
like ArrayList<String> inputList
2 :
cast it like :
String URLline = (String)inputList.get(i);
If you don't specify a type, you're using the old non-generic version. This would basically be equivalent to:
ArrayList<Object> inputList= new ArrayList<Object>();
Upvotes: 1
Reputation: 234875
You can do two things:
Make inputList
more strongly typed. Use ArrayList<String> inputList
in the function parameter list.
Use a cast at the point of use: String URLline = (String)inputList.get(i);
Be aware that (1) will cause compile time failures whereas (2) will cause runtime failures if inputList
contains objects that are not String
types. So (1) will give you more program stability but (2) will be easier to fit into your codebase, especially if you use your function getURLsContainingTarget
in many places.
Upvotes: 1
Reputation: 394156
Your inputList
is defined using a raw type - ArrayList inputList
- which means, as far as the compiler is concerned, it may contain any type of Object. Therefore, inputList.get(i)
returns Object
and not String
, and casting is required.
If you change your method signature to:
public static ArrayList<String> getURLsContainingTarget(ArrayList<String> inputList, String target) throws MalformedURLException
the casting won't be required.
Upvotes: 4