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.