简体   繁体   中英

Get a reference in “for each” java

I have this code:

ArrayList<MyClass> MyArrayList = new ArrayList<MyClass>();

for (int i = 0; i < 10; i++){
    MyClass AuxObject = new Myclass(); // Generates an object whit random properties;
    MyArrayList.add(AuxObject);
}

/*

At this point lets suposse we have the list like this

Obj1
obj2
obj3
obj4
obj5
obj6
obj7
obj8
obj9
obj10

*/


MyClass MyAuxObject = null;

for(MyClass NObject: MyArrayList){
    if(NObject.SomeBoolean == true){
       MyAuxObject = NObject; // is valid?
   break;
   }
}

My question is "MyAuxObject" will be a reference to some object on my list or gona be null? Can i use "Nobject" to get a reference to an object on the list?

Java always uses references for objects.

MyAuxObject is a reference to the same object that NObject referenced.

(That's assuming that something satisfied the if condition. Otherwise, MyAuxObject is still null .)

In this code

for(MyClass NObject: MyArrayList){
    if(MyObject.SomeBoolean == true){
       MyAuxObject = NObject; // is valid?
   break;
   }
}

you are extracting the code to an Object called NObject but doing a comparison on MyObject

I feel that this is not what you are wanting, otherwise you could just get the first element from the list.

Assuming that this is a typo, then MyAuxObject will have the value of the first matching NObject and if not matching then it will be null .

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