0% found this document useful (0 votes)
70 views

Public Class Public Static Void Final New: What Are Fail-Fast Iterators in Java? Explain With Code?

The document discusses fail-fast iterators in Java. It provides an example code that demonstrates how iterating over a list while concurrently modifying it throws a ConcurrentModificationException. This is because fail-fast iterators immediately detect changes to the underlying container to avoid inconsistent behavior. The document explains that fail-fast iterators ensure errors are found quickly rather than allowing arbitrary behavior to occur later. It also notes that changing the list during iteration, even before the loop, will still cause an exception.

Uploaded by

venu_vml
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Public Class Public Static Void Final New: What Are Fail-Fast Iterators in Java? Explain With Code?

The document discusses fail-fast iterators in Java. It provides an example code that demonstrates how iterating over a list while concurrently modifying it throws a ConcurrentModificationException. This is because fail-fast iterators immediately detect changes to the underlying container to avoid inconsistent behavior. The document explains that fail-fast iterators ensure errors are found quickly rather than allowing arbitrary behavior to occur later. It also notes that changing the list during iteration, even before the loop, will still cause an exception.

Uploaded by

venu_vml
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

What are Fail-fast Iterators in java? Explain with code?

public class FailFastIteratorTest {

public static void main(String[] args) {

final List<String> list = new ArrayList<String>();


list.add("a");
list.add("b");
list.add("c");

Iterator<String> it = list.iterator();

Thread t = new Thread() {

public void run() {


list.add("d");
list.add("e");
list.add("f");
}
};
t.start();

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}

while(it.hasNext()){
System.out.println(it.next());
}
}
}

When you run this code you get ConcurrentModificationException thrown at line
it.next()After the creation of Iterator, the container cannot be modified at any time by any
method other than the Iterator's own remove or add methods. Iterators that do this are
known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-
deterministic behavior at an undetermined time in the future.

If you change the code in the following way even then it throws the same Exception

list.add("a");
list.add("b");
list.add("c");

Iterator<String> it = list.iterator();
list.add("d");
while(it.hasNext()){
System.out.println(it.next());
}

Note: http://www.jroller.com/rajasekar/entry/java_fail_fast_iterators_exposed
You can get the detailed explanation in the above mentioned url.
Demonstrate the Hashtable class, and an Enumeration

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {

public static void main(String[] argv) {

// Construct and load the hash. This simulates loading a


// database or reading from a file, or wherever the data is.

Hashtable h = new Hashtable();

// The hash maps from company name to address.


// In real life this might map to an Address object...

h.put("Adobe", "Mountain View, CA");


h.put("IBM", "White Plains, NY");
h.put("Learning Tree", "Los Angeles, CA");
h.put("Microsoft", "Redmond, WA");
h.put("Netscape", "Mountain View, CA");
h.put("O'Reilly", "Sebastopol, CA");
h.put("Sun", "Mountain View, CA");

Enumeration k = h.keys();
while(k.hasMoreElements()) {
String key = (String) k.nextElement();
System.out.println("Key " + key ));
System.out.println(" Value " + (String) h.get(key));
}
Set set= h.keySet();
Iterator iter = set.iterator ( ) ;
int i=1;
while ( iter.hasNext () ) {
System.out.println( ""+i+" ) "+h.get (iter.next ( ))) ;
i++;
}
}
}

Comparable vs Comparator
Comparable
A comparable object is capable of comparing itself with another object. The class
itself must implements the java.lang.Comparable interface in order to be able to
compare its instances.
Comparator
A comparator object is capable of comparing two different objects. The class is not
comparing its instances, but some other class’s instances. This comparator class
must implement the java.lang.Comparator interface.
Example on Comparable

package comparable.ex01;

class Person implements Comparable {


private String firstName;
private String lastName;
private int age;

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public int compareTo(Object anotherPerson) throws ClassCastException{


if (!(anotherPerson instanceof Person))
throw new ClassCastException("A Person object expected.");
int anotherPersonAge = ((Person) anotherPerson).getAge();
return this.age - anotherPersonAge;
}
}

Testing Class

package comparable.ex01;

import java.util.Arrays;
import java.util.ArrayList;

public class Testing {

public static void main(String[] args) {


Person[] persons = new Person[4];
persons[0] = new Person();
persons[0].setFirstName("Elvis");
persons[0].setLastName("Goodyear");
persons[0].setAge(56);
persons[1] = new Person();
persons[1].setFirstName("Stanley");
persons[1].setLastName("Clark");
persons[1].setAge(8);

persons[2] = new Person();


persons[2].setFirstName("Jane");
persons[2].setLastName("Graff");
persons[2].setAge(16);

persons[3] = new Person();


persons[3].setFirstName("Nancy");
persons[3].setLastName("Goodyear");
persons[3].setAge(69);

System.out.println("Natural Order");

for (int i=0; i<4; i++) {


Person person = persons[i];
String lastName = person.getLastName();
String firstName = person.getFirstName();
int age = person.getAge();
System.out.println(lastName + ", " + firstName + ". Age:" + age);
}

Arrays.sort(persons);

System.out.println();
System.out.println("Sorted by age");

for (int i=0; i<4; i++) {


Person person = persons[i];
String lastName = person.getLastName();
String firstName = person.getFirstName();
int age = person.getAge();
System.out.println(lastName + ", " + firstName + ". Age:" + age);
}
}
}
Output
Natural Order
Goodyear, Elvis. Age:56
Clark, Stanley. Age:8
Graff, Jane. Age:16
Goodyear, Nancy. Age:69

Sorted by age
Clark, Stanley. Age:8
Graff, Jane. Age:16
Goodyear, Elvis. Age:56
Goodyear, Nancy. Age:69
Example on Compararator interface

Person Class

package comparable.ex02;

class Person implements Comparable {

private String firstName;


private String lastName;
private int age;

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public int compareTo(Object anotherPerson) throws ClassCastException{


if (!(anotherPerson instanceof Person))
throw new ClassCastException("A Person object expected.");
int anotherPersonAge = ((Person) anotherPerson).getAge();
return this.age - anotherPersonAge;
}
}
LastNameComparator Class

package comparable.ex02;

import java.util.Comparator;

public class LastNameComparator implements Comparator {

public int compare(Object person, Object anotherPerson) {


String lastName1 = ((Person) person).getLastName().toUpperCase();
String firstName1 = ((Person) person).getFirstName().toUpperCase();
String lastName2 = ((Person)anotherPerson)
.getLastName().toUpperCase();
String firstName2 = ((Person)
anotherPerson).getFirstName().toUpperCase();

if (!(lastName1.equals(lastName2)))
return lastName1.compareTo(lastName2);
else
return firstName1.compareTo(firstName2);
}
}
FirstNameComparator Class

package comparable.ex02;

import java.util.Comparator;

public class FirstNameComparator implements Comparator {


public int compare(Object person, Object anotherPerson) {
String lastName1 = ((Person) person).getLastName().toUpperCase();
String firstName1 = ((Person) person).getFirstName().toUpperCase();
String lastName2 = ((Person)
anotherPerson).getLastName().toUpperCase();
String firstName2 = ((Person)
anotherPerson).getFirstName().toUpperCase();
if (!(firstName1.equals(firstName2)))
return firstName1.compareTo(firstName2);
else
return lastName1.compareTo(lastName2);
}
}

Testing Class

package comparable.ex02;

import java.util.Arrays;
import java.util.ArrayList;

public class Testing {

public static void main(String[] args) {


Person[] persons = new Person[4];
persons[0] = new Person();
persons[0].setFirstName("Elvis");
persons[0].setLastName("Goodyear");
persons[0].setAge(56);

persons[1] = new Person();


persons[1].setFirstName("Stanley");
persons[1].setLastName("Clark");
persons[1].setAge(8);

persons[2] = new Person();


persons[2].setFirstName("Jane");
persons[2].setLastName("Graff");
persons[2].setAge(16);
persons[3] = new Person();
persons[3].setFirstName("Nancy");
persons[3].setLastName("Goodyear");
persons[3].setAge(69);

System.out.println("Natural Order");
for (int i=0; i<4; i++) {
Person person = persons[i];
String lastName = person.getLastName();
String firstName = person.getFirstName();
int age = person.getAge();
System.out.println(lastName + ", " + firstName + ". Age:" + age);
}

Arrays.sort(persons, new LastNameComparator());


System.out.println();
System.out.println("Sorted by last name");

for (int i=0; i<4; i++) {


Person person = persons[i];
String lastName = person.getLastName();
String firstName = person.getFirstName();
int age = person.getAge();
System.out.println(lastName + ", " + firstName + ". Age:" + age);
}

Arrays.sort(persons, new FirstNameComparator());


System.out.println();
System.out.println("Sorted by first name");

for (int i=0; i<4; i++) {


Person person = persons[i];
String lastName = person.getLastName();
String firstName = person.getFirstName();
int age = person.getAge();
System.out.println(lastName + ", " + firstName + ". Age:" + age);
}

Arrays.sort(persons);
System.out.println();
System.out.println("Sorted by age");

for (int i=0; i<4; i++) {


Person person = persons[i];
String lastName = person.getLastName();
String firstName = person.getFirstName();
int age = person.getAge();
System.out.println(lastName + ", " + firstName + ". Age:" + age);
}
}
}
Output

Natural Order
Goodyear, Elvis. Age:56
Clark, Stanley. Age:8
Graff, Jane. Age:16
Goodyear, Nancy. Age:69

Sorted by last name


Clark, Stanley. Age:8
Goodyear, Elvis. Age:56
Goodyear, Nancy. Age:69
Graff, Jane. Age:16

Sorted by first name


Goodyear, Elvis. Age:56
Graff, Jane. Age:16
Goodyear, Nancy. Age:69
Clark, Stanley. Age:8

Sorted by age
Clark, Stanley. Age:8
Graff, Jane. Age:16
Goodyear, Elvis. Age:56
Goodyear, Nancy. Age:69

Note: In Natural Order we did not sort the array , so elements appeared in the way
we have entered.

Demonstrate the Comparator class using a collection

import java.util.*;

class Comparer implements Comparator {


public int compare(Object obj1, Object obj2)
{
int i1 = ((Integer)obj1).intValue();
int i2 = ((Integer)obj2).intValue();

return Math.abs(i1) - Math.abs(i2);


}
}

public class collect {

public static void main(String args[]){

Vector vec = new Vector();

vec.addElement(new Integer(-200));
vec.addElement(new Integer(100));
vec.addElement(new Integer(400));
vec.addElement(new Integer(-300));

// sort by natural order


Collections.sort(vec);
for (int i = 0; i < vec.size(); i++) {
int e=((Integer)vec.elementAt(i)).intValue();
System.out.println(e);
}
// custom sort
Collections.sort(vec, new Comparer());
for (int i = 0; i < vec.size(); i++) {
int e=((Integer)vec.elementAt(i)).intValue();
System.out.println(e);

}
}
}

Note : similarly case is for arrays also. In arrays the following instruction we have to
use.
Arrays.sort(employee, new Comparer());

java.util.Collections.sort(List) and java.util.Arrays.sort(Object[])


methods can be used to sort using natural ordering of objects.

You might also like