SlideShare a Scribd company logo
1 of 34
Methods of Object class Diff. between equals and ==
toString() not overridden
// file name: Main.java
class Complex {
private double re, im;
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
}
// Driver class to test the Complex class
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
System.out.println(c1);
}
}
Output:
Complex@192123
toString() overridden
// file name: Main.java
class Complex {
private double re, im;
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
/* Returns the string representation of this Complex number. The format of string is "Re + iIm"
where Re is real part
and Im is imagenary part.*/
@Override
public String toString() {
return String.format(re + " + i" + im);
}
}
// Driver class to test the Complex class
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
System.out.println(c1);
}
}
Output:
10.0 + i15.0
 Indicates whether some other object is "equal to" this one.
Syntax:
public boolean equals(Object obj)
 If two references are identical, use ==. But when you need to know if the objects
themselves (not the references) are equal, use the equals() method.
 What It Means If You Don't Override equals() ??
The equals() method in class Object uses only the == operator for comparisons, so
unless you override equals(), two objects are considered equal only if the two
references refer to the same object.
public class Book {
...
public boolean equals(Object obj) {
if (obj instanceof Book)
return ISBN.equals((Book)obj.getISBN());
else
return false;
}
}
Book firstBook = new Book("0201914670"); //Swing Tutorial, 2nd edition
Book secondBook = new Book("0201914670");
if (firstBook.equals(secondBook)) {
System.out.println("objects are equal");
} else {
System.out.println("objects are not equal");
}
This program displays objects
are equal even though
firstBook and secondBook
reference two distinct objects.
They are considered equal
because the objects
compared contain the same
ISBN number.
You should always override
the equals() method if the
identity operator is not
appropriate for your class.
Note: If you override equals(),
you must override hashb() as
well.
An object’s hash code allows
algorithms and data structures to
put objects into compartments,
just like letter types in a printer’s
type case. The printer puts all “A”
types into the compartment for
“A”, and he looks for an “A” only
in this one compartment. This
simple system lets him find types
much faster than searching in an
unsorted drawer. That’s also the
idea of hash-based collections,
such as HashMap and HashSet.
Objects that are equal must have
the same hash code within a
running process
 If you fail to do so, you will end up with broken objects. Why? An object’s
hashCode method must take the same fields into account as its equals
method. By overriding the equals method, you’re declaring some objects
as equal to other objects, but the original hashCode method treats all
objects as different. So you will have equal objects with different hash
codes.
Whenever it is invoked on the same object more than once during an execution of
a Java application, the hashCode method must consistently return the same
integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application.
class HasHash {
public int x;
HasHash(int xVal) { x = xVal; }
public boolean equals(Object o) {
HasHash h = (HasHash) o; // Don't try at home
without
// instanceof test
if (h.x == this.x) {
return true;
} else {
return false;
}
}
public int hashCode() { return (x * 17); }
}
a. collection (lowercase c),
which represents any of the
data structures in which
objects are stored and
iterated over.
b. Collection (capital C), which
is actually the
java.util.Collection interface
from which Set, List, and
Queue extend. (That's right,
extend, not implement. There
are no direct implementations
of Collection.)
c. Collections (capital C and
ends with s) is the
java.util.Collections class that
holds a pile of static utility
methods for use with
collections.
Collections come in four basic flavors:
Lists: Lists of things (classes that
implement List).
Sets: Unique things (classes that
implement Set).
Maps: Things with a unique ID (classes
that implement Map).
Queues: Things arranged by the order in
which they are to be processed.
 Ordered When a collection is ordered, it means you can iterate through the
collection in a specific (not-random) order.
 Sorted A sorted collection means that the order in the collection is determined
according to some rule or rules, known as the sort order.
ArrayList: It is a dynamic array and can grow in size at runtime.
Example: List<String> myList = new ArrayList<String>();
myList.add(“Hello”);
Set: It does not allow duplicate elements to be stored in it.
Example: Set<String> mySet = new HashSet<>();
myList.add(“Hello”);
Map: It maintains a unique key value pair for storing elements.
Example: Map<String,String> myMap = new HashMap<String,String>();
myMap.put“Hello”,”Hello”);
Queue: It uses the FIFO mechanism to store and retrieve elements.
Example: Queue queueA = new LinkedList();
queueA.add("element 1");
queueA.add("element 2");
queueA.add("element 3");
Enumeration It is used to read values from many data structures. public abstract boolean hasMoreElements();
public abstract Object nextElement();
Iterator It is also used to read and remove values from data
structures.
public abstract boolean hasNext();
public abstract Object next();
public abstract void remove();
ListIterator It is derived from Iterator interface and comes with
more methods than Iterator. Always, subclass is richer
than super class
public abstract boolean hasNext();
public abstract void remove();
public abstract Object next();
public abstract boolean hasPrevious();
public abstract Object previous();
public abstract int nextIndex();
public abstract int previousIndex();
public abstract void set(jObject);
public abstract void add(Object);
Enumeration Iterator
Introduced with JDK 1.0 Introduced with JDK 1.2
Cannot remove any elements Can remove elements from the original DS
itselfIntroduced with JDK 1.2
Methods are hasMoreElements() and
nextElement()
Methods are hasNext() and next()
Methods are difficult to remember Methods are easy to remember
Can do remove operation only on elements Can remove, add and replace elements
Method is remove() Methods are remove(), add() and set()
iterator() method returns an object of Itertor listIterator() method returns an object of
ListItertor.
iterator() method is available for all collections.
That is, Iterator can be used for all collection
classes.
listIterator() method is available for those
collections that implement List interface. That is,
descendents of List interface only can use
ListIterator
ReturnType is int Conditions
negative thisObject <
anotherObject
zero thisObject ==
anotherObject
positive thisObject >
anotherObject
The Comparable interface is used
by the Collections.sort() method
and the java.util.Arrays.sort()
method to sort Lists and arrays of
objects, respectively. To
implement Comparable, a class
must implement a single method,
compareTo().
The sort() method uses
compareTo() to determine how
the List or object array should be
sorted. Since you get to
implement compareTo() for your
own classes, you can use
whatever weird criteria you prefer,
to sort instances of your classes.
 Methods:
public int compare(Object obj1,Object
obj2):
compares the first object with second
object.
Comparator interface is used to
order the objects of user-defined
class.
The Comparator interface gives
you the capability to sort a given
collection any number of
different ways.
It can be usd it to sort instances of
any class—even classes you can't
modify —unlike the Comparable
interface, which forces you to
change the class whose instances
you want to sort.
java.lang.Comparable java.util.Comparator
int objOne.compareTo(objTwo) int compare(objOne, objTwo)
Returns negative if objOne < objTwo zero if
objOne == objTwo positive if objOne >
objTwo
Same as Comparable
You must modify the class whose instances
you want to sort.
You build a class separate from the class
whose instances you want to sort.
Only one sort sequence can be created Many sort sequences can be created
Implemented frequently in the API by: String,
Wrapper classes, Date, Calendar...
Meant to be implemented to sort instances of
third-party classes.
 Generics was added in Java 5 to provide compile-time type checking
and removing risk of ClassCastException that was common while working
with collection classes. Generics was added in Java 5 to provide compile-
time type checking and removing risk of ClassCastException that was
common while working with collection classes.
 List myList = new ArrayList(); // can't declare a type myList.add("Fred"); //
OK, it will hold Strings
myList.add(new Dog()); // and it will hold Dogs too
myList.add(new Integer(42)); // and Integers...
 A non-generic collection can hold any kind of object! A non-generic
collection is quite happy to hold anything that is NOT a primitive
 List myList = new ArrayList();
myList.add("Fred"); // OK, it will hold Strings
myList.add(new Dog()); // compiler error!!
 By using generics syntax—which means putting the type in angle brackets
, we're telling the compiler that this collection can hold only String objects.
The type in angle brackets is referred to as either the "parameterized
type“.
List myList = new ArrayList();
becomes
List<Integer> myList = new ArrayList<Integer>();
and a list meant to hold only Strings goes from
public List changeStrings(ArrayList s) { }
to this:
public List changeStrings(ArrayList s) { }
class Main{
public static void main(String args[]){
List<Integer> in = new ArrayList<Integer>();
in.add(1);
test(in);
System.out.println(in.get(0)); //Prints 0
System.out.println(in.get(1)); // Prints hello
}
private static void test(List list){
list.add(“hello"); //String added to list
}
}
If you declare a non-generic collection, the get() method ALWAYS returns a reference of type
java.lang.Object.
 The simple rule is the type of the variable declaration must match the type
you pass to the actual object type.
 List<Parent> object = new ArrayList<Child>(); // Incorrect
 It should be:
 List<Parent> object = new ArrayList<Parent>();
Parameter declaration on left and right side must be same.
In case of method call also, only the object correct type can be passed. For
example: List<Dog> can be passed to a method expecting List<Animal> as
method argument.
 When a generic class is defined, the type parameter can be used in the
definitions of the methods for that generic class.
 In addition, a generic method can be defined that has its own type
parameter that is not the type parameter of any class
 A generic method can be a member of an ordinary class or a member of a
generic class that has some other type parameter.
 The type parameter of a generic method is local to that method, not to the
class.
 The type parameter must be placed (in angular brackets) after all the
modifiers, and before the returned type:
public static <T> T genMethod(T[] a)
 When one of these generic methods is invoked, the method name is
prefaced with the type to be plugged in, enclosed in angular brackets
String s = NonG.<String>genMethod(c);
 A generic class definition can have any number of type parameters.
 Multiple type parameters are listed in angular brackets just as in the single type
parameter case, but are separated by commas.
 Sometimes it makes sense to restrict the possible types that can be plugged in
for a type parameter T.
 For instance, to ensure that only classes that implement the Comparable interface
are plugged in for T, define a class as follows:
public class RClass<T extends Comparable>
 "extends Comparable" serves as a bound on the type parameter
T.
 Any attempt to plug in a type for T which does not implement the
Comparable interface will result in a compiler error message.
 A bound on a type may be a class name
(rather than an interface name)
 Then only descendent classes of the bounding
class may be plugged in for the type parameters:
public class ExClass<T extends Class1>
 A bounds expression may contain multiple
interfaces and up to one class.
 If there is more than one type parameter,
the syntax is as follows:
public class Two<T1 extends Class1, T2
extends Class2 & Comparable>
 Properties are configuration values managed as key/value pairs. In each pair,
the key and value are both String values. The key identifies, and is used to
retrieve, the value, much as a variable name is used to retrieve the variable's
value.
 To manage properties, create instances of java.util.Properties. This class
provides methods for the following:
 loading key/value pairs into a Properties object from a stream,
 retrieving a value from its key,
 listing the keys and their values,
 enumerating over the keys, and
 saving the properties to a stream.
 Properties extends java.util.Hashtable.

More Related Content

What's hot

Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsFrançois Garillot
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic classifis
 
Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
javaimplementation
javaimplementationjavaimplementation
javaimplementationFaRaz Ahmad
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and InformationSoftNutx
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - GenericsRoshan Deniyage
 

What's hot (20)

Java generics
Java genericsJava generics
Java generics
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Java collection
Java collectionJava collection
Java collection
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 

Viewers also liked

Atualidade 05 fevereiro de 2016.
Atualidade 05   fevereiro de 2016.Atualidade 05   fevereiro de 2016.
Atualidade 05 fevereiro de 2016.Priscila Assi
 
S.w.o.t for final pitch
S.w.o.t for final pitchS.w.o.t for final pitch
S.w.o.t for final pitchkelseytreich
 
การสร้างความจงรักภักดีต่อแบรนด์สินค้า
การสร้างความจงรักภักดีต่อแบรนด์สินค้าการสร้างความจงรักภักดีต่อแบรนด์สินค้า
การสร้างความจงรักภักดีต่อแบรนด์สินค้าZiwapohn Peecharoensap
 
Contoh soalan kps(print hand out)
Contoh soalan kps(print hand out)Contoh soalan kps(print hand out)
Contoh soalan kps(print hand out)zaikha09
 
Capitulo 17 politica de dividendo y pago
Capitulo 17 politica de dividendo y pagoCapitulo 17 politica de dividendo y pago
Capitulo 17 politica de dividendo y pagoE Andrea CG
 
A mundialização da economia grupo 2 - parte 1
A mundialização da economia   grupo 2 - parte 1A mundialização da economia   grupo 2 - parte 1
A mundialização da economia grupo 2 - parte 1Priscila Assi
 
Politicas de dividendos
Politicas de dividendosPoliticas de dividendos
Politicas de dividendosKarina Zerpa
 
Evaluation question 3
Evaluation  question 3Evaluation  question 3
Evaluation question 3a2media15b
 
Interesting case of encephalitis
Interesting case of encephalitisInteresting case of encephalitis
Interesting case of encephalitisVasif Mayan
 
Organisasi & kepimpinan
Organisasi & kepimpinanOrganisasi & kepimpinan
Organisasi & kepimpinanNuha Jr
 
Atualidades 04 a fevereiro
Atualidades   04 a   fevereiroAtualidades   04 a   fevereiro
Atualidades 04 a fevereiroPriscila Assi
 
Evaluation question 4
Evaluation question 4Evaluation question 4
Evaluation question 4freya downs
 
basic logic gates with examples in bangla
basic logic gates with examples in bangla basic logic gates with examples in bangla
basic logic gates with examples in bangla arnab73
 

Viewers also liked (15)

Atualidade 05 fevereiro de 2016.
Atualidade 05   fevereiro de 2016.Atualidade 05   fevereiro de 2016.
Atualidade 05 fevereiro de 2016.
 
TWW #2 (Eng 102)2
TWW #2 (Eng 102)2TWW #2 (Eng 102)2
TWW #2 (Eng 102)2
 
S.w.o.t for final pitch
S.w.o.t for final pitchS.w.o.t for final pitch
S.w.o.t for final pitch
 
Transforming healthcare
Transforming healthcareTransforming healthcare
Transforming healthcare
 
การสร้างความจงรักภักดีต่อแบรนด์สินค้า
การสร้างความจงรักภักดีต่อแบรนด์สินค้าการสร้างความจงรักภักดีต่อแบรนด์สินค้า
การสร้างความจงรักภักดีต่อแบรนด์สินค้า
 
Contoh soalan kps(print hand out)
Contoh soalan kps(print hand out)Contoh soalan kps(print hand out)
Contoh soalan kps(print hand out)
 
Capitulo 17 politica de dividendo y pago
Capitulo 17 politica de dividendo y pagoCapitulo 17 politica de dividendo y pago
Capitulo 17 politica de dividendo y pago
 
A mundialização da economia grupo 2 - parte 1
A mundialização da economia   grupo 2 - parte 1A mundialização da economia   grupo 2 - parte 1
A mundialização da economia grupo 2 - parte 1
 
Politicas de dividendos
Politicas de dividendosPoliticas de dividendos
Politicas de dividendos
 
Evaluation question 3
Evaluation  question 3Evaluation  question 3
Evaluation question 3
 
Interesting case of encephalitis
Interesting case of encephalitisInteresting case of encephalitis
Interesting case of encephalitis
 
Organisasi & kepimpinan
Organisasi & kepimpinanOrganisasi & kepimpinan
Organisasi & kepimpinan
 
Atualidades 04 a fevereiro
Atualidades   04 a   fevereiroAtualidades   04 a   fevereiro
Atualidades 04 a fevereiro
 
Evaluation question 4
Evaluation question 4Evaluation question 4
Evaluation question 4
 
basic logic gates with examples in bangla
basic logic gates with examples in bangla basic logic gates with examples in bangla
basic logic gates with examples in bangla
 

Similar to Collections

Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 
Collections generic
Collections genericCollections generic
Collections genericsandhish
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionssuseredfbe9
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate JavaPhilip Johnson
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdfadinathassociates
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 
The second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docxThe second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docxoreo10
 

Similar to Collections (20)

ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Collections generic
Collections genericCollections generic
Collections generic
 
Java.util
Java.utilJava.util
Java.util
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
Array properties
Array propertiesArray properties
Array properties
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Array list(1)
Array list(1)Array list(1)
Array list(1)
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
List in java
List in javaList in java
List in java
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
Java collections
Java collectionsJava collections
Java collections
 
The second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docxThe second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docx
 
Lec2
Lec2Lec2
Lec2
 

Collections

  • 1.
  • 2. Methods of Object class Diff. between equals and ==
  • 3. toString() not overridden // file name: Main.java class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; } } // Driver class to test the Complex class public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); System.out.println(c1); } } Output: Complex@192123 toString() overridden // file name: Main.java class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; } /* Returns the string representation of this Complex number. The format of string is "Re + iIm" where Re is real part and Im is imagenary part.*/ @Override public String toString() { return String.format(re + " + i" + im); } } // Driver class to test the Complex class public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); System.out.println(c1); } } Output: 10.0 + i15.0
  • 4.  Indicates whether some other object is "equal to" this one. Syntax: public boolean equals(Object obj)  If two references are identical, use ==. But when you need to know if the objects themselves (not the references) are equal, use the equals() method.  What It Means If You Don't Override equals() ?? The equals() method in class Object uses only the == operator for comparisons, so unless you override equals(), two objects are considered equal only if the two references refer to the same object.
  • 5. public class Book { ... public boolean equals(Object obj) { if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false; } } Book firstBook = new Book("0201914670"); //Swing Tutorial, 2nd edition Book secondBook = new Book("0201914670"); if (firstBook.equals(secondBook)) { System.out.println("objects are equal"); } else { System.out.println("objects are not equal"); } This program displays objects are equal even though firstBook and secondBook reference two distinct objects. They are considered equal because the objects compared contain the same ISBN number. You should always override the equals() method if the identity operator is not appropriate for your class. Note: If you override equals(), you must override hashb() as well.
  • 6. An object’s hash code allows algorithms and data structures to put objects into compartments, just like letter types in a printer’s type case. The printer puts all “A” types into the compartment for “A”, and he looks for an “A” only in this one compartment. This simple system lets him find types much faster than searching in an unsorted drawer. That’s also the idea of hash-based collections, such as HashMap and HashSet. Objects that are equal must have the same hash code within a running process
  • 7.  If you fail to do so, you will end up with broken objects. Why? An object’s hashCode method must take the same fields into account as its equals method. By overriding the equals method, you’re declaring some objects as equal to other objects, but the original hashCode method treats all objects as different. So you will have equal objects with different hash codes. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • 8. class HasHash { public int x; HasHash(int xVal) { x = xVal; } public boolean equals(Object o) { HasHash h = (HasHash) o; // Don't try at home without // instanceof test if (h.x == this.x) { return true; } else { return false; } } public int hashCode() { return (x * 17); } }
  • 9. a. collection (lowercase c), which represents any of the data structures in which objects are stored and iterated over. b. Collection (capital C), which is actually the java.util.Collection interface from which Set, List, and Queue extend. (That's right, extend, not implement. There are no direct implementations of Collection.) c. Collections (capital C and ends with s) is the java.util.Collections class that holds a pile of static utility methods for use with collections.
  • 10. Collections come in four basic flavors: Lists: Lists of things (classes that implement List). Sets: Unique things (classes that implement Set). Maps: Things with a unique ID (classes that implement Map). Queues: Things arranged by the order in which they are to be processed.
  • 11.  Ordered When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order.  Sorted A sorted collection means that the order in the collection is determined according to some rule or rules, known as the sort order.
  • 12. ArrayList: It is a dynamic array and can grow in size at runtime. Example: List<String> myList = new ArrayList<String>(); myList.add(“Hello”); Set: It does not allow duplicate elements to be stored in it. Example: Set<String> mySet = new HashSet<>(); myList.add(“Hello”); Map: It maintains a unique key value pair for storing elements. Example: Map<String,String> myMap = new HashMap<String,String>(); myMap.put“Hello”,”Hello”); Queue: It uses the FIFO mechanism to store and retrieve elements. Example: Queue queueA = new LinkedList(); queueA.add("element 1"); queueA.add("element 2"); queueA.add("element 3");
  • 13.
  • 14. Enumeration It is used to read values from many data structures. public abstract boolean hasMoreElements(); public abstract Object nextElement(); Iterator It is also used to read and remove values from data structures. public abstract boolean hasNext(); public abstract Object next(); public abstract void remove(); ListIterator It is derived from Iterator interface and comes with more methods than Iterator. Always, subclass is richer than super class public abstract boolean hasNext(); public abstract void remove(); public abstract Object next(); public abstract boolean hasPrevious(); public abstract Object previous(); public abstract int nextIndex(); public abstract int previousIndex(); public abstract void set(jObject); public abstract void add(Object);
  • 15. Enumeration Iterator Introduced with JDK 1.0 Introduced with JDK 1.2 Cannot remove any elements Can remove elements from the original DS itselfIntroduced with JDK 1.2 Methods are hasMoreElements() and nextElement() Methods are hasNext() and next() Methods are difficult to remember Methods are easy to remember Can do remove operation only on elements Can remove, add and replace elements Method is remove() Methods are remove(), add() and set() iterator() method returns an object of Itertor listIterator() method returns an object of ListItertor. iterator() method is available for all collections. That is, Iterator can be used for all collection classes. listIterator() method is available for those collections that implement List interface. That is, descendents of List interface only can use ListIterator
  • 16. ReturnType is int Conditions negative thisObject < anotherObject zero thisObject == anotherObject positive thisObject > anotherObject The Comparable interface is used by the Collections.sort() method and the java.util.Arrays.sort() method to sort Lists and arrays of objects, respectively. To implement Comparable, a class must implement a single method, compareTo(). The sort() method uses compareTo() to determine how the List or object array should be sorted. Since you get to implement compareTo() for your own classes, you can use whatever weird criteria you prefer, to sort instances of your classes.
  • 17.  Methods: public int compare(Object obj1,Object obj2): compares the first object with second object. Comparator interface is used to order the objects of user-defined class. The Comparator interface gives you the capability to sort a given collection any number of different ways. It can be usd it to sort instances of any class—even classes you can't modify —unlike the Comparable interface, which forces you to change the class whose instances you want to sort.
  • 18. java.lang.Comparable java.util.Comparator int objOne.compareTo(objTwo) int compare(objOne, objTwo) Returns negative if objOne < objTwo zero if objOne == objTwo positive if objOne > objTwo Same as Comparable You must modify the class whose instances you want to sort. You build a class separate from the class whose instances you want to sort. Only one sort sequence can be created Many sort sequences can be created Implemented frequently in the API by: String, Wrapper classes, Date, Calendar... Meant to be implemented to sort instances of third-party classes.
  • 19.  Generics was added in Java 5 to provide compile-time type checking and removing risk of ClassCastException that was common while working with collection classes. Generics was added in Java 5 to provide compile- time type checking and removing risk of ClassCastException that was common while working with collection classes.
  • 20.  List myList = new ArrayList(); // can't declare a type myList.add("Fred"); // OK, it will hold Strings myList.add(new Dog()); // and it will hold Dogs too myList.add(new Integer(42)); // and Integers...  A non-generic collection can hold any kind of object! A non-generic collection is quite happy to hold anything that is NOT a primitive
  • 21.  List myList = new ArrayList(); myList.add("Fred"); // OK, it will hold Strings myList.add(new Dog()); // compiler error!!  By using generics syntax—which means putting the type in angle brackets , we're telling the compiler that this collection can hold only String objects. The type in angle brackets is referred to as either the "parameterized type“.
  • 22. List myList = new ArrayList(); becomes List<Integer> myList = new ArrayList<Integer>(); and a list meant to hold only Strings goes from public List changeStrings(ArrayList s) { } to this: public List changeStrings(ArrayList s) { }
  • 23. class Main{ public static void main(String args[]){ List<Integer> in = new ArrayList<Integer>(); in.add(1); test(in); System.out.println(in.get(0)); //Prints 0 System.out.println(in.get(1)); // Prints hello } private static void test(List list){ list.add(“hello"); //String added to list } } If you declare a non-generic collection, the get() method ALWAYS returns a reference of type java.lang.Object.
  • 24.  The simple rule is the type of the variable declaration must match the type you pass to the actual object type.  List<Parent> object = new ArrayList<Child>(); // Incorrect  It should be:  List<Parent> object = new ArrayList<Parent>(); Parameter declaration on left and right side must be same. In case of method call also, only the object correct type can be passed. For example: List<Dog> can be passed to a method expecting List<Animal> as method argument.
  • 25.  When a generic class is defined, the type parameter can be used in the definitions of the methods for that generic class.  In addition, a generic method can be defined that has its own type parameter that is not the type parameter of any class  A generic method can be a member of an ordinary class or a member of a generic class that has some other type parameter.  The type parameter of a generic method is local to that method, not to the class.
  • 26.  The type parameter must be placed (in angular brackets) after all the modifiers, and before the returned type: public static <T> T genMethod(T[] a)  When one of these generic methods is invoked, the method name is prefaced with the type to be plugged in, enclosed in angular brackets String s = NonG.<String>genMethod(c);
  • 27.
  • 28.
  • 29.
  • 30.  A generic class definition can have any number of type parameters.  Multiple type parameters are listed in angular brackets just as in the single type parameter case, but are separated by commas.
  • 31.
  • 32.  Sometimes it makes sense to restrict the possible types that can be plugged in for a type parameter T.  For instance, to ensure that only classes that implement the Comparable interface are plugged in for T, define a class as follows: public class RClass<T extends Comparable>  "extends Comparable" serves as a bound on the type parameter T.  Any attempt to plug in a type for T which does not implement the Comparable interface will result in a compiler error message.
  • 33.  A bound on a type may be a class name (rather than an interface name)  Then only descendent classes of the bounding class may be plugged in for the type parameters: public class ExClass<T extends Class1>  A bounds expression may contain multiple interfaces and up to one class.  If there is more than one type parameter, the syntax is as follows: public class Two<T1 extends Class1, T2 extends Class2 & Comparable>
  • 34.  Properties are configuration values managed as key/value pairs. In each pair, the key and value are both String values. The key identifies, and is used to retrieve, the value, much as a variable name is used to retrieve the variable's value.  To manage properties, create instances of java.util.Properties. This class provides methods for the following:  loading key/value pairs into a Properties object from a stream,  retrieving a value from its key,  listing the keys and their values,  enumerating over the keys, and  saving the properties to a stream.  Properties extends java.util.Hashtable.