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

Exception

The document contains code examples demonstrating the use of Comparator and Comparable interfaces in Java to sort collections of objects. It shows how to write comparator classes to sort ArrayLists of custom HDTV objects by size and brand. It also shows how to implement Comparable on a custom class to enable natural sorting by size. The examples illustrate how to override equals() and hashCode() to properly compare objects in collections like HashSet.

Uploaded by

Ngô Hoàng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Exception

The document contains code examples demonstrating the use of Comparator and Comparable interfaces in Java to sort collections of objects. It shows how to write comparator classes to sort ArrayLists of custom HDTV objects by size and brand. It also shows how to implement Comparable on a custom class to enable natural sorting by size. The examples illustrate how to override equals() and hashCode() to properly compare objects in collections like HashSet.

Uploaded by

Ngô Hoàng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

package collectionTest;

import java.util.LinkedList;
import java.util.Queue;

public class QueueTest {

public static void main(String[] args) {

TestLinkedList.testIt();
}

class TestLinkedList{

public static void testIt() {

Queue<Integer> queue=new LinkedList<Integer>();

for(int i=0;i<=5;i++) {
queue.add(i);
}
System.out.println("Printing Before operations...");
System.out.println(queue.size());
System.out.println(queue);

// System.out.println("Poll operation...");
// queue.poll();
//
// System.out.println(queue.size());
// System.out.println(queue);

System.out.println("Peek operation...");
queue.peek();

System.out.println(queue.size());
System.out.println(queue);

}
}
---------------------

package collections2.comparableANDcomparator;

//Comparator interface Example

//Comparator interface is used to compare "two different objects"

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

class HDTV { // POJO class

private int size;


private String brand;
HDTV(int size, String brand) {

this.size = size;
this.brand = brand;
}

public int getSize() {


return size;
}

public void setSize(int size) {


this.size = size;
}

public String getBrand() {


return brand;
}

public void setBrand(String brand) {


this.brand = brand;
}

class SizeComparator implements Comparator<HDTV> {

public int compare(HDTV tv1, HDTV tv2) {

int tv1Size = tv1.getSize();


int tv2Size = tv2.getSize();

if (tv1Size > tv2Size)


return 1;
else if (tv1Size < tv2Size)
return -1;
else
return 0;

}
}

class BrandComparator implements Comparator<HDTV> {

public int compare(HDTV tv1, HDTV tv2) {

String tv1Brand = tv1.getBrand();


String tv2Brand = tv2.getBrand();

int a=tv1Brand.compareTo(tv2Brand);

return a;

}
}

public class ComparatorTest {

public static void main(String[] args) {


HDTV tv1 = new HDTV(55, "Samsung"); // A-65, a-97
HDTV tv2 = new HDTV(60, "Sony");
HDTV tv3 = new HDTV(42, "Panasonic");
HDTV tv4 = new HDTV(77, "LG");

ArrayList<HDTV> al = new ArrayList<HDTV>();

al.add(tv1);
al.add(tv2);
al.add(tv3);
al.add(tv4);

// Collections.sort() and Arrays.sort();

System.out.println("Before Sorting..............");
Iterator<HDTV> itrr=al.iterator();
while (itrr.hasNext()) {

HDTV tv=itrr.next();
System.out.println(tv.getSize()+"\t"+tv.getBrand());
}

Collections.sort(al,new SizeComparator());

System.out.println("After Sorting..............");
Iterator<HDTV> itr=al.iterator();
while (itr.hasNext()) {

HDTV tv=itr.next();
System.out.println(tv.getSize()+"\t"+tv.getBrand());
}

System.out.println("---------------------------------------------");

System.out.println("Before Sorting..............");
for (HDTV a : al) {

System.out.println(a.getBrand());
}

System.out.println("---------------------------------------------");

Collections.sort(al, new BrandComparator());

System.out.println("After Sorting..............");
for (HDTV a : al) {

System.out.println(a.getBrand());
}

}
}
--------------
package comparableANDcomparator;

//Comparable interface example

//By Default implemented by String and


//Wrapper classes(Integer,Float,Byte,Short,Character,Long ...)

class HDTVV implements Comparable<HDTVV> {

private int size;


private String brand;

HDTVV(int size, String brand) {

this.size = size;
this.brand = brand;

System.out.println("inside constructor size is:"+this.size);


System.out.println("inside constructor brand is:"+this.brand);

System.out.println("------------------------------------------"+"\n");

public int getSize() {


return size;
}

public void setSize(int size) {


this.size = size;
}

public String getBrand() {


return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}

@Override
public int compareTo(HDTVV tv) {

if (this.getSize() > tv.getSize())


return 1;
else if (this.getSize() < tv.getSize())
return -1;
else
return 0;
}

public class ComparableTest {

public static void main(String[] args) {

HDTVV tv1 = new HDTVV(60, "Samsung");


HDTVV tv2 = new HDTVV(80, "Sony");

System.out.println("TV1 Size is----"+tv1.getSize());


System.out.println("TV2 Size is----"+tv2.getSize());

/*
if (tv1.compareTo(tv2)>0) {

System.out.println(tv1.getBrand() + " is better.");


System.out.println("------------------------------"+"\n");
}
else {
System.out.println("------------------------------"+"\n");
System.out.println(tv2.getBrand() + " is better.");
}*/
int a=tv1.compareTo(tv2); //60 and 80
System.out.println(a); // -1

int b=tv2.compareTo(tv1);
System.out.println(b); // 1

if(a>b)
{
System.out.println(tv1.getBrand() + " is better.");

}else if (a<b) {

System.out.println(tv2.getBrand() + " is better.");

}else {

System.out.println("both are of equal size");

}
}
---------------

package collections2.equalsandhashcode;

public class PrimitiveEqualTest {

public static void main(String[] args) {

int a=3;
int b=3;

String s1="abc"; //literals


String s2="abc";

if(s1==s2)
System.out.println("s1 and s2 are equal");
else
System.out.println("s1 and s2 are not equal");

if(a==b)
System.out.println("a and b are equal");
else
System.out.println("a and b are not equal");

}
------------

package collections2.equalsandhashcode;

import java.util.ArrayList;
import java.util.HashSet;

//If we want to compare two objects based upon equals() method, then
//we have to override both equals() and hashCode() .

class Emp extends Object


{
int age;

Emp(int age)
{
System.out.println("Emp constructor called......"+age);

this.age=age;

@Override
public boolean equals(Object o)
{
Emp e=(Emp)o;

if(this.age==e.age)
return true;
else
return false;

@Override
public int hashCode()
{
return age;
}
}

public class EqualsHashCodeTest1 {

public static void main(String[] args) {

System.out.println("Starting main.....");

Emp e1=new Emp(22);


Emp e2=new Emp(23);

HashSet<Object> hs=new HashSet<Object>();


hs.add(e1);
hs.add(e2);
System.out.println(hs.contains(new Emp(22))); // false

ArrayList<Object> al=new ArrayList<Object>();


al.add(e1);
al.add(e2);
System.out.println(al.contains(new Emp(22))); // false

System.out.println("Ending main.....");

}
-----------------

package collections2.equalsandhashcode;

import java.util.ArrayList;
import java.util.HashSet;

//If we want to compare two objects based upon equals() method, then
//we have to override both equals() and hashCode() .
class Emp extends Object
{
int age;

Emp(int age)
{
System.out.println("Emp constructor called......"+age);

this.age=age;

@Override
public boolean equals(Object o)
{
Emp e=(Emp)o;

if(this.age==e.age)
return true;
else
return false;

@Override
public int hashCode()
{
return age;
}
}

public class EqualsHashCodeTest1 {

public static void main(String[] args) {

System.out.println("Starting main.....");

Emp e1=new Emp(22);


Emp e2=new Emp(23);

HashSet<Object> hs=new HashSet<Object>();


hs.add(e1);
hs.add(e2);
System.out.println(hs.contains(new Emp(22))); // false

ArrayList<Object> al=new ArrayList<Object>();


al.add(e1);
al.add(e2);
System.out.println(al.contains(new Emp(22))); // false

System.out.println("Ending main.....");

}
----------------

import java.util.*;

public class Main {


public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int s[]= new int[100];
System.out.println("Enter the number of seats to be booked:");
int seats= sc.nextInt();
System.out.println("Enter the seat number 1");
int n= sc.nextInt();
System.out.println("Enter the seat number 2");
int n2= sc.nextInt();
System.out.println("Enter the seat number 3");
int n3= sc.nextInt();
System.out.println("Enter the seat number 4");
int n4= sc.nextInt();
System.out.println("Enter the seat number 5");
int n5= sc.nextInt();
try {
s[5]= 5;
System.out.println("The seats booked are: "+s);

}catch (ArrayIndexOutOfBoundsException e){


System.out.println(e);

}
}
}
-------------------

import java.util.*;
public class ArrayException {
public int size,index;
public int arr[];
public String getPriceDetails()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements in the array");
try {
size=sc.nextInt();
size=Integer.parseInt(String.valueOf(size));
arr=new int[size];
System.out.println("Enter the price details");
for(int i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the index of the array element you want to
access");
index=sc.nextInt();
return("The array element is "+arr[index]);

}
catch(ArrayIndexOutOfBoundsException e)
{
return("Array index is out of range");
}
catch(InputMismatchException e)
{
return("Input was not in the correct format");
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
ArrayException ex=new ArrayException();
System.out.println(ex.getPriceDetails());
}
}
---------------------------

You might also like