Java INt
Java INt
Java INt
Ans: )
1) Synchronization - ArrayList is not thread-safe whereas Vector is
thread-safe. In Vector class each method like add(), get(int i) is
surrounded with a synchronized block and thus making Vector
class thread-safe.
2) Data growth - Internally, both the ArrayList and Vector hold
onto their contents using an Array. When an element is inserted
into an ArrayList or a Vector, the object will need to expand its
internal array if it runs out of room. A Vector defaults to doubling
the size of its array, while the ArrayList increases its array size by
50 percent.
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1]; // 3 dimensional
array
When to use ArrayList or LinkedList ?
Ans) Adding new elements is pretty fast for either type of list. For
the ArrayList, doing random lookup using "get" is fast, but for
LinkedList, it's slow. It's slow because there's no efficient way to
index into the middle of a linked list. When removing elements,
using ArrayList is slow. This is because all remaining elements in
the underlying array of Object instances must be shifted down for
each remove operation. But here LinkedList is fast, because
deletion can be done simply by changing a couple of links. So an
ArrayList works best for cases where you're doing random access
on the list, and a LinkedList works better if you're doing a lot of
editing in the middle of the list.
Source : Read More - from java.sun
Consider a scenario. If an ArrayList has to be iterate to read data
only, what are the possible ways and which is the fastest?
Ans) It can be done in two ways, using for loop or using iterator of
ArrayList. The first option is faster than using iterator. Because
value stored in arraylist is indexed access. So while accessing the
value is accessed directly from the index.
Now another question with respect to above question is if
accessing through iterator is slow then why do we need it and
when to use it.
Ans) For loop does not allow the updation in the array(add or
remove operation) inside the loop whereas Iterator does. Also
Iterator can be used where there is no clue what type of
collections will be used because all collections have iterator.
Security Restrictions
Reflection requires a runtime permission which may
not be present when running under a security
manager. This is in an important consideration for
code which has to run in a restricted security context,
such as in an Applet.
Exposure of Internals
Since reflection allows code to perform operations that
would be illegal in non-reflective code, such as
accessing private fields and methods, the use of
reflection can result in unexpected side-effects, which
may render code dysfunctional and may destroy
portability. Reflective code breaks abstractions and
therefore may change behavior with upgrades of the
platform.
Comparable Example
class Employee implements Comparable{
private int age;
public void setAge(int age){
this.age=age;
}
public int getAge(){
return this.age;
}
/*
Signature of compareTo method is.
public int compareTo(Object object).
compareTo method should return 0 if both objects are equal, 1 if first
grater than other and -1 if first less than the other object of the same
class.
*/
public int compareTo(Object otherEmployee){
/*
return 1;
else if ( this.getAge() < age )
return -1;
else
return 0;
}
}
public class JavaComparableExample{
public static void main(String args[]){
/*
Create two different Employee objects, so that we can compare both.
*/
Employee one = new Employee();
one.setAge(40);
Employee two = new Employee();
one.setAge(30);
/*
Use compareTo method to determine which employee is younger
*/
if( one.compareTo(two) > 0 ) {
System.out.println("Employee one is elder than employee two !");
} else if( one.compareTo(two) < 0 ) {
System.out.println("Employee one is younger than employee two !");
} else( one.compareTo(two) == 0 ) {
System.out.println("Both employees are same !");
}
}
}
/*
OUTPUT of the above given Java Comparable Example would be :
Employee one is elder than employee two !
*/
Comparator Example
/*
Java Comparator example.
This Java Comparator example describes how java.util.Comparator interface
is implemented to compare Java user defined classe's objects.
These Java Comparator is passed to Collection's sorting method ( for
example Collections.sort method)to perform sorting of Java user defined
classe's objects.
*/
import java.util.*;
/*
java.util.Comparator interface declares two methods,
1) public int compare(Object object1, Object object2) and
2) boolean equals(Object object)
*/
/*
We will compare objects of the Employee class using custom comparators
on the basis of employee age and name.
*/
class Employee{
private int age;
private String name;
public void setAge (int age){
this.age=age;
}
public int getAge(){
return this.age;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
}
/*
User defined java comaprator.
To create custom java comparator Implement Comparator interface and
define compare method.
The below given comparator compares employees on the basis of their age.
*/
class AgeComparator implements Comparator{
public int compare(Object emp1, Object emp2){
//parameter are of type Object, so we have to downcast it to Employee
objects
int emp1Age = ( (Employee) emp1).getAge();
int emp2Age = ( (Employee) emp2).getAge();
if( emp1Age > emp2Age )
return 1;
else if( emp1Age < emp2Age )
return -1;
else
return 0;
}
}
/*
The below given comparator compares employees on the basis of their name.
*/
class NameComparator implements Comparator{
public int compare(Object emp1, Object emp2){
//parameter are of type Object, so we have to downcast it to Employee
objects
*/
/*
Sorting array on the basis of employee age by passing AgeComparator
*/
Arrays.sort(employee, new AgeComparator());
System.out.println("\n\nOrder of employee after sorting by employee age
is");
for(int i=0; i < employee.length; i++){
System.out.println( "Employee " + (i+1) + " name :: " +
employee[i].getName() + ", Age :: " + employee[i].getAge());
}
/*
Sorting array on the basis of employee Name by passing NameComparator
*/
Arrays.sort(employee, new NameComparator());
System.out.println("\n\nOrder of employee after sorting by employee name
is");
for(int i=0; i < employee.length; i++){
System.out.println( "Employee " + (i+1) + " name :: " +
employee[i].getName() + ", Age :: " + employee[i].getAge());
}
}
}
/*
OUTPUT of the above given Java Comparable Example would be :
Order of employee before sorting is
Employee 1 name :: Joe, Age :: 40
Employee 2 name :: Mark, Age :: 20
Order of employee after sorting by employee age is
Employee 1 name :: Mark, Age :: 20
Employee 2 name :: Joe, Age :: 40
Order of employee after sorting by employee name is
Employee 1 name :: Joe, Age :: 40
Employee 2 name :: Mark, Age :: 20
*/
2.
3.
2.
zero o1 equals to o2
3.
Next well create a list of Employees for using in different sorting requirements. Employees are added
to a List without any specific order in the following class.
import java.util.*;
The new compareTo() method does the trick of implementing the natural ordering of the instances. So
if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens
according to the ordering done inside this method.
Well write a class to test this natural ordering mechanism. Following class use the
Collections.sort(List) method to sort the given list in natural order.
import java.util.*;
Run the above class and examine the output. It will be as follows. As you can see, the list is sorted
correctly using the employee id. As empId is an int value, the employee instances are ordered so that
the int values ordered from 1 to 8.
EmpId Name Age
1 Jorge 19
2 Mark 30
3 Michel 10
4 Clerk 16
5 Frank 28
6 Bill 34
7 Simp 8
8 Lee 40
By writing a class that implements the java.lang.Comparator interface, you can sort Employees using
any field as you wish even without touching the Employee class itself; Employee class does not need
to implement java.lang.Comparable or java.lang.Comparator interface.
Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method
instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how
the EmpSortByName comparator is used inside sort method.
import java.util.*;
}
}
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name
String field. Youll see that these are sorted alphabetically.