APEX: Adding equals and hashCode Methods to Your Class
HashCode:
Class with equal and hashCode methods:
global with sharing class AtestClass {
class TempratureReading {
public TempratureReading(String city,Integer reading ){
this.city = city;
this.reading= reading;
}
public String hashCode(){
return this.city+this.reading;
}
public Boolean equals(Object obj) {
TempratureReading other = (TempratureReading)obj;
if(other.city.contains(this.city))
return true;
else
return false;
}
String city{get;set;}
Integer reading{get;set;}
}
List<TempratureReading> readingsOfTheDay(){
List<TempratureReading> dayReadings = new List<TempratureReading>();
dayReadings.add(new TempratureReading('NewYork',111111111));
dayReadings.add(new TempratureReading('Paris',222222222));
dayReadings.add(new TempratureReading('NewYork',333333333));
dayReadings.add(new TempratureReading('Paris',444444444));
return dayReadings;
}
public void findMaxTemp() {
Map<TempratureReading,Integer> mapReading = new Map<TempratureReading,Integer>();
for(TempratureReading trRec :readingsOfTheDay()){
mapReading.put(trRec,trRec.reading);
}
for(TempratureReading trRec : mapReading.keySet()){
System.debug( trRec.city + ' -- ' + mapReading.get(trRec));
}
}
}
execute this following
AtestClass a = new AtestClass();
a.findMaxTemp();
Class with equal and hashCode methods:
global with sharing class AtestClass {
class TempratureReading {
public TempratureReading(String city,Integer reading ){
this.city = city;
this.reading= reading;
}
public String hashCode(){
return this.city+this.reading;
}
public Boolean equals(Object obj) {
TempratureReading other = (TempratureReading)obj;
if(other.city.contains(this.city))
return true;
else
return false;
}
String city{get;set;}
Integer reading{get;set;}
}
List<TempratureReading> readingsOfTheDay(){
List<TempratureReading> dayReadings = new List<TempratureReading>();
dayReadings.add(new TempratureReading('NewYork',111111111));
dayReadings.add(new TempratureReading('Paris',222222222));
dayReadings.add(new TempratureReading('NewYork',333333333));
dayReadings.add(new TempratureReading('Paris',444444444));
return dayReadings;
}
public void findMaxTemp() {
Map<TempratureReading,Integer> mapReading = new Map<TempratureReading,Integer>();
for(TempratureReading trRec :readingsOfTheDay()){
mapReading.put(trRec,trRec.reading);
}
for(TempratureReading trRec : mapReading.keySet()){
System.debug( trRec.city + ' -- ' + mapReading.get(trRec));
}
}
}
execute this following
AtestClass a = new AtestClass();
a.findMaxTemp();
Comments
Post a Comment