2: Explain the differences of Test04 and Test05 briely. a import java.util.Array
ID: 3581006 • Letter: 2
Question
2: Explain the differences of Test04 and Test05 briely.
a
import java.util.ArrayList;
public class Test04 {
public static void main(String [] args) {
ArrayList<Integer> a1 = new ArrayList<>();
a1.add(new Integer(1));
a1.add(new Integer(2));
a1.add(new Integer(3));
ArrayList<Integer> a2 = a1;
a2.add(new Integer(4));
System.out.println(a1);
System.out.println(a2);
} }
output:
[1, 2, 3, 4]
[1, 2, 3, 4]
b
import java.util.ArrayList;
public class Test05 {
public static void main(String [] args) {
ArrayList<Integer> a1 = new ArrayList<>();
a1.add(new Integer(1));
a1.add(new Integer(2));
a1.add(new Integer(3));
ArrayList<Integer> a2 = new ArrayList<>(a1);
a2.add(new Integer(4));
System.out.println(a1);
System.out.println(a2);
} }
output:
[1, 2, 3]
[1, 2, 3, 4]
Explanation / Answer
To understand the difference you first need to know one thing i.e
when an object to a class is just defined without allocating any memmory to it
ie class_name var;//here var will be reference variable.
then it becomes a referance variable. referance variables are used as aliases to the varibles that are assigned to them
var = new class1_name();
so now var will refer to members of class1_name.
similarly
class_name var2= new class_name();
var=var2;
then var is used to access var2 i.e it is another way to use var2.
now comming to the programme
a) the statement
ArrayList<Integer> a2 = a1;
means that we are creating a2 as an alias to al.
i.e a2 also points to a1.
whenever we try to add something to a2 that means we are actually adding it to a1 only
so both a1 and a2 will be same.
b)
ArrayList<Integer> a2 = new ArrayList<>(a1);
this statement creates a arraylist a2 by invoking the parameterised constructor of ArrayList class and copies the values of ArrayList a1 to a2.
so here a1 and a2 are two different variables, modification of one object does not effect the other.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.