Created
September 21, 2015 16:52
-
-
Save ee08b397/9ebb7cee5e12486ba5b7 to your computer and use it in GitHub Desktop.
Java call-by-value, pass arrays/autoboxing
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.LinkedList; | |
import java.util.ListIterator; | |
public class ObjPass { | |
public static void change_int(Integer i) { | |
i = 1000; | |
} | |
public static void change_string(String a) { | |
a = "changed"; | |
} | |
public static void change_array(int[] a) { | |
a[0] = 10; | |
} | |
public static void change_linkedList(LinkedList<String> linkedList) { | |
linkedList.set(0, "changed"); | |
} | |
public static void solution() { | |
// integer | |
Integer integer = new Integer(10); | |
change_int(integer); | |
System.out.println("integer = " + integer); | |
// string | |
String string = "a string"; | |
change_string(string); | |
System.out.println(string); | |
// array | |
int[] a = {0,1,2,3,4}; | |
change_array(a); | |
for (int e : a) | |
System.out.print(e + " "); | |
System.out.println(); | |
// linked list | |
LinkedList<String> linkedList = new LinkedList<String>(); | |
linkedList.add("eBay"); | |
linkedList.add("Paypal"); | |
linkedList.add("Google"); | |
linkedList.add("Yahoo"); | |
linkedList.add("IBM"); | |
linkedList.add("Facebook"); | |
change_linkedList(linkedList); | |
for (int i = 0; i < linkedList.size(); i++) | |
System.out.print(linkedList.get(i) + " "); | |
System.out.println(); | |
//ListIterator<String> listIterator = linkedList.listIterator(); | |
//while (listIterator.hasNext()) { | |
// System.out.print(listIterator.next() + " "); | |
//} | |
for(ListIterator listIterator = linkedList.listIterator(); listIterator.hasNext();) { | |
System.out.print(listIterator.next() + " "); | |
} | |
System.out.println(); | |
for (String str: linkedList) { | |
System.out.print(str + " "); | |
} | |
System.out.println(); | |
} | |
public static void main(String[] args) { | |
solution(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
Only array and linked list are updated. The others are autoboxing primitives http://beginnersbook.com/2014/09/java-autoboxing-and-unboxing-with-examples/.
For other data structures that may get updated
