Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Creating the MVP Strings and Chars

Ciaran McNally
Ciaran McNally
7,052 Points

Which is the better way

I completed the challenge with the following code;

boolean hasT = mHand.indexOf(tile) >= 0 ;

if(hasT){
return true;
}else{
return false;
}

I understand why this works. Although initially I tried to use the mHand.contains(tile) below

if(mHand.contains(tile)){
return true;
}
etc...

this give me a compile error. Another user had pointed out in another question that this requires a string and would work if you used mHand.contains("" +tile)

Can someone please explain the difference between the two ways of doing it? what would be the better way and why do you need to concatenate in the argument

Thanks

1 Answer

Benjamin Barslev Nielsen
Benjamin Barslev Nielsen
18,958 Points

Personally I would prefer using the contains method, since I find that code more readable. Using the indexOf approach, I need to understand that code before knowing, that it actually just checks if tile is contained in mHand.

By looking at contains in the API for Strings we see that it takes a CharSequence, which is an interface that is implemented by String. Therefore we use:

"" + tile

to perform a conversion from the type char to the type String. Note that tile has type char and ""+tile has type String. Since String implements CharSequence it can be given as a argument to contains.

Btw, this code:

if(hasT){
    return true;
}else{
    return false;
}

could be written as:

return hasT;
Ciaran McNally
Ciaran McNally
7,052 Points

Thanks for reply. I can see now how return hasT works. It's taking me some time to get my head round Java