gerii
gerii

Reputation: 29

Why is this ArrayList being treated as a list of objects?

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 Objects instead of Strings.

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 ArrayLists are always defined as Strings.

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

Answers (3)

user3145373 ツ
user3145373 ツ

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

Bathsheba
Bathsheba

Reputation: 234875

You can do two things:

  1. Make inputList more strongly typed. Use ArrayList<String> inputList in the function parameter list.

  2. 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

Eran
Eran

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

Related Questions