1

I can't seem to wrap my head around why the compiler is telling me that is can't convert from Object to List but it already is a List. Could someone point out what I'm not seeing?

import java.util.List;
import java.util.ArrayList;

public class User {
    private List<String> subscribed;

    public User() {
        this.subscribed = new ArrayList<String>();
    }

    public List<String> getSubscribed() {
        return ((ArrayList<String>)subscribed).clone();
    }
}
  • 2
    What are you casting? `subscribed` or the return value of `clone()`? – Sotirios Delimanolis Jul 25 '15 at 01:40
  • `Object.clone()` is considered broken, so don't use it. Instead use a copy constructor for creating a new list. More info in [Clone() vs Copy constructor- which is recommended in java](http://stackoverflow.com/questions/2427883/clone-vs-copy-constructor-which-is-recommended-in-java). – Mick Mnemonic Jul 25 '15 at 01:48

3 Answers3

3

clone() returns a reference of type Object (which is thus incompatible with the return type of your method). You could cast, but it's more idiomatic to do something like this:

public List<String> getSubscribed() {
    return new ArrayList<String>(subscribed);
}
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • Thank you! I didn't even think about creating a new ArrayList. Part of the exercise was to become familiar with the ArrayList API, and I think I might have been a bit too enthusiastic about using as many API methods as I could. – Frank Gallagher Jul 25 '15 at 01:49
2

Following is the declaration for java.util.ArrayList.clone() method

public Object clone()

So, this statement return ((ArrayList<String>)subscribed).clone(); is returning an Object type from the method which was expected to return a List.

Hence, the compiler is complaining about it.

You should cast subscribed.clone() to ArrayList<String> and return this value.

This would work in your public List<String> getSubscribed() {...} method

return (ArrayList<String>)(subscribed).clone());
Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
1

clone() is a method declared in the interface Cloneable, and it's return type is declared as Object. Since ArrayList implements this interface, it's clone method also returns an Object.

Thus you have to confirm to the compiler that you are in fact returning a List, because for all it knows, the method clone() in ArrayList returns an Object:

 public List<String> getSubscribed() {
    return (List<String>)((ArrayList<String>)subscribed).clone();
}