Guilherme Soares
Guilherme Soares

Reputation: 736

JAVA cast to Object to ArrayList doesn't work

About problem

Eventually when i try cast Object to ArrayList i've problem when i use method from ArrayList like .size(), .get():

That the error returned to me:

error: cannot find symbol

Source

public String parseValueParam(Object value) throws InvalidAttribute{

        if(value instanceof ArrayList){
            value =  (ArrayList) value;

            String result = ""; 

            for(int i = 0, _len = value.size(); i < _len; i ++){
                result += this.parseValueParam(value.get(i));
                if (i < _len - 1)   result += " , ";
            };
            return result;

        } else if(helper.isString(value)){
        
            return value.toString().replaceAll("'", "");

        } else if (helper.isInteger(value) || helper.isDouble(value)){
        
            return value.toString();

        } else {
        
            throw new InvalidAttribute("Invalid attribute type");
        }
    }

I've tried to declare couple of methods with same name one using Object to accept String, Int and Double and another only accept ArrayList. However when i run my code execute only the use Object.

public String parseValueParam(ArrayList value) throws InvalidAttribute{

    String result = ""; 
    for(int i = 0, _len = value.size(); i < _len; i ++){
        result += this.parseValueParam(value.get(i));
        if (i < _len - 1)   result += " , ";
    };
    return result;
}

Upvotes: 0

Views: 1086

Answers (2)

Mitch Talmadge
Mitch Talmadge

Reputation: 4755

The problem is that even though you are casting value to ArrayList here:

value =  (ArrayList) value;

The variable value is still declared to be an Object, so casting really did nothing for you.

You need to make a new variable, like this:

ArrayList list = (ArrayList) value;

Then just use the new variable, list.

Upvotes: 0

afzalex
afzalex

Reputation: 8652

value is declared to be of Object type.
when you explicitly parsed it to ArrayList object, you still have assigned it to value variable. The type of value is still Object, it cannot be changed.
Use another variable of ArrayList, and use that variable instead.

ArrayList value2;
if(value instanceof ArrayList){
    value2 =  (ArrayList) value;
    String result = ""; 

    for(int i = 0, _len = value2.size(); i < _len; i ++){
     ....

Upvotes: 3

Related Questions