Sei sulla pagina 1di 12

Collections Questions

List - This data structure is used to contain list of elements. In case you need list of elements and
the list may contain duplicate values, then you have to use List.
Ex :- lists are ordered, and you can have duplicates.
i.e. you add A B C A D, and if you iterate through, you'll get A B C A D right bac.
Map - It contains data as key value pair. When you have to store data in key value pair, so that
latter you can retrieve data using the key, you have to use Map data structure.!ou can have
duplicate values, but not duplicate eys.
E". - na#e $ fred
age $ %%
dogsna#e $ fred
Set - It has some similarities with List, but it can't contain duplicate elements. So when you need a
set of data where duplicates are not allowed, you need this data structure.
Ex :- &ets are unordered, and you can't have duplicates.
&o if you add A B C A D, you could get bac A B C D or A C B D etc.
Diff. Between Hash Map and Has Set :-
Hash Map Hash Set
HashMap is a implementation of Map
interface
HashSet is an implementation of Set
Interface
HashMap Stores data in form of key
value pair
HashSet Store only objects
Put method is used to add element in
map
Add method is used to add element is
Set
In hash map hashcode value is
calculated using key object
Here member object is used
forcalculating hashcode value which can
be same for two objects so equal !
method is used to check for equality ifit
returns false that means two objects are
different"
HashMap is faster than hashset
because unique key is used to access
object
HashSet is slower than Hashmap
Page | 1
Similarity Between Hash Map & Hash Table :-
1) Both Hashtable and HashMap implements java.util.Map interface.
2) Hashtable and HashMap both are hash based collection and wors on principle of
hashing.
!) Hashtable and HashMap both provide constant time performance for put and get
method if objects are distributed uniforml" across bucet.
#) $rom %&' # both Hashtable and HashMap are part of %ava collection framewor.
Diff. Between Hash Map & Hash Table :-
'( )irst and #ost significant different bet*een Hashtable and HashMap is that, +ash,ap is not thread-
safe *hile +ashtable is a thread-safe collection.
%( &econd i#portant difference bet*een +ashtable and +ash,ap is perfor#ance, since +ash,ap is not
synchroni-ed it perfor# better than +ashtable.
.( /hird difference on +ashtable vs +ash,ap is that +ashtable is obsolete class and you should be using
Concurrent+ash,ap in place of +ashtable in 0ava.
#) And# a third difference is that HashMap permits null values in it# while Hashtable doesn$t"
Dif. Between Linked List & Array List :-
') (ince )rra" is an inde* based data+structure searching or getting element from
)rra" with inde* is prett" fast. )rra" provides ,-1) performance for get-inde*)
method but remove is costl" in )rra".ist as "ou need to rearrange all elements. ,n
the ,ther hand .ined.ist doesn/t provide 0andom or inde* based access and "ou
need to iterate over lined list to retrieve an" element which is of order ,-n).
2) 1nsertions are eas" and fast in .ined.ist as compared to )rra".ist because
there is no ris of resi2ing arra"
and cop"ing content to new arra" if arra" gets full which maes adding into
)rra".ist of ,-n) in worst case3 while adding is ,-1) operation in .ined.ist in %ava.
)rra".ist also needs to update its inde* if "ou insert something an"where e*cept at
the end of arra".
!) 0emoval is lie insertions better in .ined.ist than )rra".ist.
#) .ined.ist has more memor" overhead than )rra".ist because in )rra".ist each
inde* onl" holds actual object -data) but in case of .ined.ist each node holds both
data and address of ne*t and previous node.
Page | 2
Dif. Between LinkedHashSet & HashSet :-
LinkedHashSet A %inkedHashSet is an ordered version of HashSet that
maintains a doubly&linked %ist across all elements" 'se this class instead of HashSet
when you care about the iteration order" (hen you iterate through a HashSet the
order is unpredictable# while a %inkedHashSet lets you iterate through the elements
in the order in which they were inserted"
HashSet A HashSet is an unsorted# unordered Set" It uses the hashcode
of the object being inserted# so the more efficient your hash)ode! implementation
the better access performance you$ll get" 'se this class when you want a collection
with no duplicates and you don$t care about order when you iterate through it"
Diference between HashSet!reeSet and LinkedHashSet
TreeSet is ordered and sorted.HashSet is not ordered and not sorted.LinkedHashSet is an
ordered HashSet.
As per Java specs LinkedHashset should give nearly the same performance as HashSet -
But HashSet is usually faster.HashSet is faster than TreeSet also.
LinkedHashSet - the elements are ordered by the insertion.Treeset has an ascending
order.
'( Duplicates : All three i#ple#ents &et interface #eans they are not allo*ed to store
duplicates.
%( Thread safety : HashSet, TreeSet and LinkedHashSet are not thread-safe .
null 4 Both Hash(et and .inedHash(et allows null but 5ree(et doesn/t allow
null but 5ree(et doesn/t allow null and
throw java.lang.6ullPointer7*ception when "ou will insert null into 5ree(et.
LinkedHashMap and HashMap in Java - Similarities
1) Both .inedHashMap and HashMap are not s"nchroni2ed and subject to
race condition if shared between multiple threads without proper
s"nchroni2ation. 8se 9ollections.s"nchroni2edMap-) for maing them
s"nchroni2ed.
2) 1terator returned b" HashMap and .inedHashMap are fail+fast in nature.
!) Performance of HashMap and .inedHashMap are similar also.
Page | !
LinkedHashMap and HashMap & TreeMap in Java Difference
1) $irst and foremost di:erence between .inedHashMap and HashMap is
order3 HashMap doesn/t maintain an" order while.inedHashMap maintains
insertion order of elements in %ava.
2) .inedHashMap also re;uires more memor" than HashMap because of this
ordering feature. )s 1 said before .inedHashMapuses doubl" .ined.ist to
eep order of elements.
!) .inedHashMap actuall" e*tends HashMap and implements Map
interface.
TreeMap- /ree,ap eeps the ite#s in order si#ilar to sorting. /ree,ap creates a tree structure
to eep all ite#s sorted based on their eys. /o co#pare bet*een t*o eys, it uses
co#pare/o1( #ethod of ey ob2ects. /ree,ap does i#ple#ent and additional interface,
&orted,ap.
1. HashMap<String, String> a=new HashMap<String, String>();
2. a.put(a, apple);
!. a.put(b, banana);
". a.put(#,#$li%l$&er);
'.
(.
). Set<String> b= a.ke*Set();
+.
,. for(String #- b)
1.. S*ste/.$ut.println(#);
*utput b#a#c
1. LinkedHashMap<String, String> a=new LinkedHashMap<String, String>();
2. a.put(a, apple);
!. a.put(b, banana);
". a.put(#,#$li%l$&er);
'.
(.
). Set<String> b= a.ke*Set();
+.
,. for(String #- b)
Page | #
1.. S*ste/.$ut.println(#);
*utput + a#b#c
Similarity & Difference Between Vector & Array List in Java :
Similarities :
'( 0e#t$r and 1rra*List are index based and baced up by an array internally.
%( Both Array3ist and 4ector #aintains the insertion order of ele#ent. ,eans you can assu#e
that you *ill get the ob2ect in the order you have inserted if you iterate over Array3ist or 4ector.
.( Both 5terator and 3ist5terator returned by ArrayList and Vector are fail-fast.
6( 1rra*List and 0e#t$r also allo*s null and duplicates.
Difference :
1) Synchrni!atin and thread-safety
)irst and fore#ost difference bet*een 4ector and Array3ist is that "ectr is synchrni!ed and
Array3ist is not,
#) Speed and $erfrmance
1rra*List is *ay faster than 0e#t$r% &ince 4ector is synchroni-ed and thread-safe it pays
price of synchroni-ation *hich #aes it little slo*.
&) 'apacity
7henever 4ector crossed the threshold specified it increases itself by value specified
in #apa#it*2n#re/ent field *hile you can increase si-e of Array3ist by
calling ensure3apa#it* () #ethod.
Page | <
Difference Between !terator & "n#meration !nterface in Java :
1- Only major difference between Enumeration and iterator is Iterator has a remove()
method while Enumeration doesn't.
2- Enumeration acts as Read-only interface, because it has the methods only to traverse and
fetch the objects, where as by usin Iterator we can mani!ulate the objects li"e addin and
removin the objects from collection e.. #rraylist.
3- #lso Iterator is more secure and safe as com!ared to n!meration because it does not
allow other thread to modify the collection object while some thread is iteratin over it and
throws "on#!rrentMo$ifi#ation%#eption.
n!meration
has$oreElement()
ne%tElement()
Iterator
has&e%t()
ne%t()
remove()
Page | =
JAVA !$%"&V!"' ()"S%!*$S
1% 889& concept
#% ,ultithreading concept
&% Collection )ra#e*or
(% Exception handling
)% Differentiate co#parator and co#parable in 2ava
*% Difference bet*een vector and array list: 5s vector synchroni-ed:
+% &ynchroni-ation in 2ava
,% Design pattern is 0ava 1&tress #ore on &ingleton class(
-% threads cycle
1.% Differentiate +ash table and +ash #ap
11% 0ava Classes
1#% 9ass by value and pass by reference in 0ava
13. Difference between final, finalized and finally
14. Sleep method
15. Connection pooling
16. JDBC Drivers- Types ? oading iss!es
17. Br!sh on the technologies yo! !sed in the most recent pro"ects
#$- e,plain architecture of you r project -
./& (hat is Spring - what are advantages of using spring -
01& what is Inversion of control -
0.& what is difference between hibernate and 234c-
00& how many modules are present in spring-
05& how do u write configuration file using hibernate-
06& how do u map pojo clasess with respect to database-
07& what happens when object is created in java-
08& what is abstarct class-
09& what is polymorphism-
0:& what is method overloading and method over riding-
0/& what is data abstraction-
Page | >
51& what is encapsulation-
5.& what is 'M%- 'nified modeling language!
50& what is differernce between interpreted code and compiled code-
55& what is collections - e,plain %ist # Set # Map-
56& what is Servlet - %ife )ycle of Servlet-
57& differrence between servlet config and servlet conter,t-
58& can we call constructor of abstract class-
59& can we define constructor in abstract class-
5:& what is difference between forward and send redirect-
5/& whar is differrence between do;<= and doPost-
61& how to call a jsp page from servlet-
6.& what is difference between comparator and comparable-
60& what is sysnchroni>ation in java-
65& what is session tracking-
66& what is primary key #foreign key#unique key-
67& wha are constraints -
68& what are inde,es- e,plain difference between clustered and nonclustered inde,s-
69& e,plain any case where we dont define any inde,es on table-
6:& what is normali>ation- why do we require to do normali>ation on table -
6/& what are interfaces-
71& what is difference between abstract class and interfaces-
7.& e,plain difference between construnctor and method-

70& what are pass by reference and pass by value-
75& what is vector and arraylist e,plain difference between them
76& what is static# final in java-
77& e,plain public # private #protected # default scopes-
78& what is e,ceptions in java e,plain checked and unchecked e,ception -
79& what is ,sd-
7:& what is ,ml-
7/& e,plain 3*M- document object module-
81& e,plain difference between declaring variable and definig variable-
8.& difference between ?? and equals !
80& what are scriptlest - what are implicit objects -
85& what are e,presions-
86& difference between variable declared inside a declaration part and variable declared inside a
scriptlet part-
87& what is preinitiali>ation of servlet-
88& what are joins - inner# left outer # right outer #full outer joins-
89& e,plain the role of servlet dispatcher -
Page | ?
Differentiate /et0een 'mparatr and 'mpara1le 2nterface 3-
Co"#arable $nter%ace has @co"#are!o@ method which is normall" used for
natural ordering.
Ahen "ou need natural sort order "ou can implement the 9omparable interface.
i/p$rt 4a5a.util.6;

#lass 7/pl$*ee i/ple/ents 3$/parable<7/pl$*ee> 8
pri5ate int e/p2d;

publi# int #$/pareT$(7/pl$*ee $) 8
return this.e/p2d 9 $.e/p2d ;
:
...
:

publi# #lass 3$/parableTest
8
publi# stati# 5$id /ain(String;< args)
8

7/pl$*ee e/p1 = ne& 7/pl$*ee();
e/p1.set7/p2d(2);
7/pl$*ee e/p2 = ne& 7/pl$*ee();
e/p2.set7/p2d(1);
7/pl$*ee e/p! = ne& 7/pl$*ee();
e/p!.set7/p2d(!);

List lst = ne& 1rra*List();
Page | B
lst.add(e/p1);
lst.add(e/p2);
lst.add(e/p!);

S*ste/.$ut.println(=e%$re S$rt - >lst);

3$lle#ti$ns.s$rt(lst);

S*ste/.$ut.println(1%ter S$rt - >lst);
:
:
&!tp!t
'efore (ort ) *+, ,, -.
#fter (ort ) *,, +, -.
Co"#arator $nter%ace has @co"#are@ method which taes two arguments. 1t can
be used where "ou want to sort objects based of more then one parameter.
1f Cou want an alternate sort order or sorting on di:erent properties then implement
a 9omparator for "our class.
i/p$rt 4a5a.util.6;

#lass 7/pl$*ee 8
pri5ate String na/e;
...
:

#lass 7/pS$rt=*?a/e i/ple/ents 3$/parat$r<7/pl$*ee> 8
publi# int #$/pare(7/pl$*ee $1, 7/pl$*ee $2) 8
return $1.get?a/e().#$/pareT$($2.get?a/e());
:
:

publi# #lass 3$/parat$rTest
8
publi# stati# 5$id /ain(String;< args)
8
7/pl$*ee e/p1 = ne& 7/pl$*ee();
e/p1.set?a/e(=);
7/pl$*ee e/p2 = ne& 7/pl$*ee();
e/p2.set?a/e(1);
7/pl$*ee e/p! = ne& 7/pl$*ee();
e/p!.set?a/e(3);

List lst = ne& 1rra*List();
lst.add(e/p1);
Page | 1D
lst.add(e/p2);
lst.add(e/p!);

S*ste/.$ut.println(=e%$re S$rt - >lst);

3$lle#ti$ns.s$rt(lst,ne& 7/pS$rt=*?a/e());

S*ste/.$ut.println(1%ter S$rt - >lst);

:
:
&!tp!t
'efore (ort ) *', #, /.
#fter (ort ) *#, ', /.
"om "omparableparable "omparator"omparator
/lass whose objects which we need to sort
must im!lement java.lan./om!arable
interface #ompareTo'&b(e#t o1) metho$
.*.
If we want to sort Em!loyee, our em!loyee
class needs to im!lement above method.
/lass whose objects which we need to sort $o
not nee$ to implement any interfa#e metho$.
.*.
If we want to sort Em!loyee objects usin
em!loyee name, 0e write a class
Em!(ort'y&ame which im!lements
java.util./om!arator interface#ompare'&b(e#t
o1+&b(e#t o2) metho$
Sortin* lo*i# is in the same #lass whose
objects are bein sorted. 1ence this is called
&atural orderin of objects.
Sortin* lo*i# is in separate #lass. 1ence we can
write different sortin based on different
attributes of objects to be sorted. E.. (ortin
usin name, last name, ae etc.
0e use /ollections.sort(2ist) method to
sortin.
.*
"olle#tions.sort'list),
0e must use the /ollections.sort(2ist,
/om!arator) for sortin.
.*.
"olle#tions.sort'list+ new mpSortBy-ame')),
(a.a.lan*."omparable: int #ompareTo'&b(e#t
o1)
3his method com!ares this object with o,
object. Returned int value has the followin
meanins.
,. !ositive 4 this object is reater than o,
+. 5ero 4 this object e6uals to o,
(a.a.!til."omparator: int #ompare'&b(e#t o1+
&b(e#to2)
3his method com!ares o, and o+ objects.
Returned int value has the followin meanins.
,. !ositive 4 o, is reater than o+
+. 5ero 4 o, e6uals to o+
-. neative 4 o, is less than o,
Page | 11
-. neative 4 this object is less than o,
&a"e '% Classes & $nter%ace in Collection :-
Classes $nter%ace
(- HashMap 9ollection3 (et3 (orted(et
)-Hash5able .ist3 Eueue
*-5reeMap Map3 (ortedMap
+-Fector
,-)rra".ist
--.in.ist
.-(tac
/-.inHashMap
0-Hash(et3 5ree(et3
.inedHash(et
Page | 12

Potrebbero piacerti anche