Created
July 17, 2013 14:53
-
-
Save EdgeCaseBerg/6021298 to your computer and use it in GitHub Desktop.
Demonstration that objects within a list are passed by reference to any other list they're appended to. In other words:
List 1 = [ Object1, Object2, Object3 ... ObjectN ]
List 2 = [] List 2 .add ( some object from List 1 ) List 2 will have a reference to the same object in List 1.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
public class ListReference{ | |
public static int id = 0; | |
protected static class MyLittleObject{ | |
public int val; | |
public MyLittleObject(){this.val=ListReference.id; ListReference.id +=1; } | |
} | |
public static void main(String[] args) { | |
List<MyLittleObject> outer = new ArrayList<MyLittleObject>(); | |
for(int i=0; i < 10; i++){ | |
outer.add(new MyLittleObject()); | |
} | |
//Print it | |
System.out.println("initial array: "); | |
for(final MyLittleObject o : outer){ | |
System.out.print("|" + o + "( " + o.val + ") | "); | |
} | |
System.out.println(""); | |
ListReference.func1(outer); | |
} | |
public static void func1(Collection<MyLittleObject> friends){ | |
//We have this list of things and now we're going to pass it over somewhere else | |
List<MyLittleObject> chunk = new ArrayList<MyLittleObject>(); | |
List<MyLittleObject> toAppendTo = new ArrayList<MyLittleObject>(); | |
for(final MyLittleObject o : friends){ | |
chunk.add(o); | |
if(chunk.size() == 3){ //minimal example | |
toAppendTo.addAll(ListReference.func2(chunk)); | |
chunk.clear(); | |
} | |
} | |
if(!chunk.isEmpty()) | |
toAppendTo.addAll(ListReference.func2(chunk)); | |
//Now print the toAppendTo | |
System.out.println("Array that will be returned"); | |
for(final MyLittleObject o : toAppendTo) | |
System.out.print("|" + o + "( " + o.val + ") | "); | |
System.out.println(""); | |
//What's in chunk? | |
System.out.println("Chunk array"); | |
for(final MyLittleObject o : chunk) | |
System.out.print("|" + o + "( " + o.val + ") | "); | |
System.out.println(""); | |
} | |
public static Collection<MyLittleObject> func2(Collection<MyLittleObject> chunks){ | |
List<MyLittleObject> hold = new ArrayList<MyLittleObject>(); | |
//Take the chunk and put some of it into hold | |
for(final MyLittleObject o : chunks ){ | |
if(o.val % 3 == 0) | |
hold.add(o); | |
} | |
//Return the list. | |
return hold; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment