In: Computer Science
JAVA LANGUAGE
ArrayList<Integer> al = new ArrayList<Integer>();
HashSet<Integer> hs = new HashSet<Integer>();
HashMap<Integer, Integer> hm = new HashMap<Integer,Integer>();
for (int i= 0; i<2; i++) {
al.add(i);
al.add(i+1);
hs.add(i);
hs.add(i+1);
hm.put(al.get(i), al.get(i+1));
hm.put(hm.get(i), hm.get(i+1));
}
System.out.println(al);
System.out.println(hs);
System.out.println(hm); // {key=value}.
----------------------------------
What output is produced by the following code and why?
Note :
The code is in java .
code :
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class integer { public static void main (String [] args) { ArrayList<Integer> al = new ArrayList<Integer>(); HashSet<Integer> hs = new HashSet<Integer>(); HashMap<Integer, Integer> hm = new HashMap<Integer,Integer>(); for (int i= 0; i<2; i++) { al.add(i); al.add(i+1); hs.add(i); hs.add(i+1); hm.put(al.get(i), al.get(i+1)); hm.put(hm.get(i), hm.get(i+1)); } System.out.println(al); System.out.println(hs); System.out.println(hm); // {key=value}. } }
ouput:
[0, 1, 1, 2]
[0, 1, 2]
{0=1, 1=null}
code(SS):
ouput(SS):
Explain:
ArrayList
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i= 0; i<2; i++) { al.add(i); al.add(i+1);
}
In the for loop we assign i= 0 and value of i will execute upto 1 because it less than 2 , hence in 1st iteration the output will ,
al.add(0)=0
al.sdd(0+1)=1
n 2nd iteration the output will ,
al.add(1)=1
al.add(1+1)=2
hence output is : [0, 1, 1, 2]
HashSet :
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
The concept is same as arraylist but it doent allow duplicate hence it remove duplicate '1' from output,
and output is :
[0, 1, 2]
HashMap :
HashMap is an implementation of Map Interface, which map key to value.
Duplicate keys are not allowed in a map.
Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains order of the objects but HashMap will not.HashMap allows null values and null keys.
and outpurt is:
{0=1, 1=null}