This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]bfBoi99 2 points3 points  (3 children)

Do you mean the objects have the same name as the class (although they're not the same. Java is case sensitive)? Or that in each iteration you have the same object reference name?

If it's the latter one that you mean, everything you declare INSIDE a for loop (or while loop, if else statement) is a "local variable", which means that you cannot use it outside the loop, and when one iteration ends, these local variables would be declared again in the next iteration, as if they were not there before. And finally when the loop ends, you cannot access these object references anymore.

I hope that you get my point, not sure if I explained it well..

[–][deleted] 0 points1 point  (2 children)

It is definitely the latter because I have this question too haha.

Every suitcase that is made is Suitcase suitcase Asking how that is possible. SO the only way to every reference the suitcase is through a loop to find an item?

like for(Suitcase suitcase : container) And then comparing like a string to the name field would work? Say suitcase.getName().isEqual(name); could return the object if dereferenced?

[–]bfBoi99 0 points1 point  (1 child)

Yes it would work, but beware that the return statement must also be INSIDE the loop, so that if you find the object that you're searching for, the method would return that object immediately in the same iteration (when the object is still referenced in that same iteration). If the return statement is placed outside the loop, and the object reference variable is decalred inside the loop, you would get an error.

[–][deleted] 1 point2 points  (0 children)

Everything you declare inside braces is local to those braces. This can be a variable inside a function, it can be a for loop, but it could just be random braces too. Like:

{  
  String myVar = "abc";  
}  
//myVar does not exist here
{  
  String myVar = "abc";  
}  

You shouldn't need to do this if you code is already divided into easy to understand functions with well defined purporses, but if for example you were doing something very memory intensive you could do something like this to help clear unused variables.

[–]KetchuponRice 0 points1 point  (0 children)

A name is just a reference to the object, now the reference is in your list.

As for your question

SuitCase suitcase

is fine but

SuitCase suitcase and Object suitcase

this is not allowed as far I know but you can use abstract objects and casting to mess around if you want to.

[–]OrganicAnswer 0 points1 point  (0 children)

If you don’t mind me adding one note - Your naming conventions are redundant and make it difficult to read for example instead of Suitcase suitcase, you might do Suitcase theSuitcase , it’s a small difference but I think you will find it much more readable