简体   繁体   中英

accessing object inside array object java

I'm new to java, I did search for a solution and didn't found it.

I have "Trip [] _data" array of Trip objects.

"Trip" object is using "Date" class to represent the trip departure dates, Inside Trip class theres a boolean method "sameDepartureDate" that get a Trip object and done equalization, If it's got same departure day as this.object.

I have public method inside "Date" called "equals". Its getting Date object and done the equal to this.object.

The sameDepartureDate method inside Trip class are:

    public boolean sameDepartureDate (Trip other){
    if ((_departureDate.equals(other._departureDate)))
        return true;
    else return false;
} 

I need to check how many Trips inside the array is using the same departure dates.

in other words, if a given "Date object" is equals to the array[i] date object inside trip object. (using equals method from Date class, or using "sameDepartureDate" from Trip class)

How can i call a method from the Trip/Date class inside the array object to check with a Date object?

I tried to build a method like this, But I get an error "inconvertible types, Required: Date, found: boolean"

public int howManyTripsDeparture(Date date){
    //Setting default!
    int j=0;
    int i;

    if (date==null){
        return j;
    } 

    else for (i=0; i<_data.length; i++){  
            if (_data[i]==null){
                j=j;
            }
            else if ((Date) _data[i].equals(date)){ //here is the problem :/
                j=j++; 
            }
            else j=j;
    }
    return j;

}

It's homework, Therefor I cant build new methods inside Trip/Date class.

I can build new private methods as I wish inside the current class.

I cant figure out how to cast the _data[i] into a "Date" object??? I don't need the other data it's contained when I done the equalization.

Thanks for the help:-)

You were almost there, just change this:

else if (_data[i].getDepartureDate().equals(date)){ //here is the problem :/
      j=j++; 
}

Just remove that (Date) casting that you are doing inside the else if because if requires a boolean inside the bracket

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM