MainMenu

Home Java Overview Maven Tutorials

Saturday 12 October 2024

Generics in Java with Example




Hello Friends,

Generics , This concept, introduced in JDK 5.0

Generics in Java are a powerful feature that allows you to define classes, interfaces, and methods with type parameters. This means that you can write flexible and reusable code while maintaining type safety, as it helps prevent runtime type casting errors by catching them at compile time.


Advantages of Generics:

Type Safety: Compile-time type checks prevent runtime ClassCastException.
Code Reusability: You can write a generic class or method once and use it for different data types.
Elimination of Casts: When retrieving elements from a generic collection, there's no need to cast the result.




Generic Class Example:




import java.util.*;

class A<T>{
private T item;
public A(T item){
this.item=item;
}
public void set(T item){
this.item = item;
}
public T get(){
return item;
}
}

public class GenericDemo {
public static void main(String[] args){
ArrayList list = new ArrayList();
list.add(24);
// list.add("www.way2testing.com");
// list.add(new HashSet());
int x = list.get(0);
System.out.println(x);
A obj = new A("csc");
// obj.set("way2testing");
System.out.println(obj.get());
}
}

Output:


Generic Methods:

In Java, generic methods are methods that are written with a parameterized type, enabling them to operate on objects of various types while still being type-safe. The key feature of generics is that they allow you to write a method or class that can handle any data type, without sacrificing compile-time type checking.

Advantages of Generic Methods:

Type Safety: You get compile-time type checking and avoid ClassCastException. Code Reusability: A single generic method can be used for different data types, avoiding duplication.

Generic Methods Example:



public class GenericMethod {
public static <T> void gtest(T[] arr){
for(T a:arr){
System.out.println(a);
}
System.out.println("Generic Methods");
}

public static void main(String[] args){
Integer[] ia = {1,2,3,4,5};
gtest(ia);
String[] sa = {"csc", "way2testing", "datastop", "dbshop"};
gtest(sa);
}
}







Generic Interface:


In Java, a generic interface is an interface that can work with any type of data using type parameters. This allows the interface to be type-safe and reusable for different types, similar to generic classes and methods.



Generic Interface Example:



interface genricEngine<T>{
void set(T item);
T get();
}
class car implements genricEngine<String>{
private String accessories;
public void set(String accessories){
this.accessories = accessories;
}
@Override
public String get() {
return accessories;
}
}
class suv implements genricEngine<Integer>{
private Integer gear;
public void set(Integer gear){
this.gear = gear;
}
@Override
public Integer get() {
return gear;
}
}
public class InterfaceGeneric {
public static void main(String[] args){
car a = new car();
a.set("nitrogen");
System.out.println(a.get());
suv b = new suv();
b.set(5);
System.out.println(b.get());
}
}






Friday 11 October 2024

Comparable and Comparator Interface in Java




Hello Friends,

In java, when we want to sort a collection, we use Class “Collections” and static method “sort()”
For example : List list = new ArraysList();
Collections.sort(list);
Now all the elements of the list will be sorted as per alphabetic order or numeric order.
But what if a list has objects then list items will be compared and which one will go first in list??
So , to sort the objects, we need to specify a rule based on that object should be sorted.
The “Comparator” and “Comparable” interface allow us to specify what rule is used to sort the objects.

FeatureComparableComparator
Interfacejava.lang.Comparablejava.util.Comparator
MethodcompareTo(T o)compare(T o1, T o2)
Natural OrderDefines natural ordering within the classDefines custom ordering outside the class
Single/MultipleCan only have one natural orderCan define multiple comparison methods
UsageUsed when you have one "natural" way to compareUsed for custom sorting logic or multiple comparisons


1. Comparable Interface

Purpose: Used to define a natural ordering of objects.
Method: Requires implementation of the method compareTo(Object o).
Usage: A class implements Comparable when its objects are supposed to be ordered in a natural way (e.g., alphabetical for strings, numerical for numbers).
Modification: This affects the class itself, meaning the comparison logic is part of the class definition.



2. Comparator Interface

Purpose: Used to define a custom or multiple orderings for objects.
Method: Requires implementation of the method compare(Object o1, Object o2).
Usage: Comparator is typically used when you want to define multiple ways of comparing objects or when you want to compare objects of a class that you do not control (e.g., a library class).
Modification: The comparison logic is external to the class being compared.

Comparable with example :




public class Vehicle implements Comparable<Vehicle>{
private int vehiclenumber;
private String vehiclename;
private int vehicleyear;
public Vehicle(int vehiclenumber, String vehiclename, int vehicleyear){
this.vehiclenumber = vehiclenumber;
this.vehiclename = vehiclename;
this.vehicleyear = vehicleyear;
}
public String toString(){
return "vehicle{"+
"vehiclenumber='" + vehiclenumber+ '\''+
", vehiclename='" + vehiclename+ '\''+
", vehicleyear=" + vehicleyear+
'}';
}

@Override
public int compareTo(@NotNull Vehicle o) {
return this.vehiclenumber - o.vehiclenumber;
}
}

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class comparatordemoa {
public static void main(String[] args){
List list = new ArrayList();
list.add(10);
list.add(20);
list.add(9);
list.add(15);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
List list2 = new ArrayList();
list2.add(new vehical(2345, "ford", 2024));
list2.add(new vehical(3456, "kia", 2023));
list2.add(new vehical(5678, "suzuki", 2025));
System.out.println(list2);
Collections.sort(list2);
System.out.println(list2);
}
}

Comparator with example :

public class Vehicle2 {
public int getVehiclenumber() {
return vehiclenumber;
}
public void setVehiclenumber(int vehiclenumber) {
this.vehiclenumber = vehiclenumber;
}
public String getVehiclename() {
return vehiclename;
}
public void setVehiclename(String vehiclename) {
this.vehiclename = vehiclename;
}
public int getVehicleyear() {
return vehicleyear;
}

public void setVehicleyear(int vehicleyear) {
this.vehicleyear = vehicleyear;
}

private int vehiclenumber;
private String vehiclename;
private int vehicleyear;

public Vehicle2(int vehiclenumber, String vehiclename, int vehicleyear){
this.vehiclenumber = vehiclenumber;
this.vehiclename = vehiclename;
this.vehicleyear = vehicleyear;
}

public String toString(){
return "vehicle{"+
"vehiclenumber='" + vehiclenumber+ '\''+
", vehiclename='" + vehiclename+ '\''+
", vehicleyear=" + vehicleyear+
'}';
}
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparableDemo {
public static void main(String[] args){
List list = new ArrayList();
list.add("Amit");
list.add("Baji");
list.add("Nishant");
list.add("Diraaj");
list.add("Chandan");
System.out.println(list);
Collections.sort(list);
System.out.println(list);
List list1 = new ArrayList();
list1.add(new Vehicle(10,"ford", 2022));
list1.add(new Vehicle(15,"Hundai", 2023));
list1.add(new Vehicle(5,"Honda", 2026));
System.out.println(list1);
Collections.sort(list1);
System.out.println(list1);
List list2 = new ArrayList();
list2.add(new Vehicle2(10,"City", 2022));
list2.add(new Vehicle2(15,"Baleno", 2023));
list2.add(new Vehicle2(5,"Accent", 2026));
System.out.println(list2);
Collections.sort(list2, new CompratorDemo());
System.out.println(list2);
}
}

public class CompratorDemo implements Comparator<Vehicle2> {

@Override
public int compare(Vehicle2 o1, Vehicle2 o2) {
return o1.getVehiclename().compareTo(o2.getVehiclename());
}
}

Example :


Tags:

Example of Comparable interface in java

Example of Comparator interface in java

Comparable vs comparator in java

Adavntage of Comparator over Comparable interface in java