1. , :
public static List<String> difference(Student s1, Student s2) {
List<String> res = new ArrayList<>();
if (!s1.name.equalsIgnoreCase(s2.name)) res.add("name");
if (s1.age != s2.age) res.add("age");
res.addAll(Address.difference(s1.address, s2.address));
return res;
}
public static List<String> difference(Address s1, Address s2) {
List<String> res = new ArrayList<>();
if (!s1.hno.equalsIgnoreCase(s2.hno)) res.add("adress.hno");
if (!s1.street.equalsIgnoreCase(s2.street)) res.add("adress.street");
if (s1.pin != s2.pin) res.add("pin");
return res;
}
: [age, adress.hno, adress.street]
,
List<String> list = Student.difference(s1, s2);
System.out.println(list);
2.. , , :
private static List<String> difference(Student s1, Student s2) throws IllegalAccessException {
List<String> res = new ArrayList<>();
for (Field f : s1.getClass().getFields())
if (!f.get(s1).equals(f.get(s2)))
res.add(f.getName());
return res;
}
: [address, age]
, ,
List<String> list = difference(s1, s2);
System.out.println(list);
3. :
constructor
attributs
,- public
getters
setters
equals
class Student {
private String name; private Address address; private int age;
public Student (String n, Address ad, int a){name = n; address = ad; age=a;}
}
class Address {
private String hno; private String street; private int pin;
public Address (String a, String s, int p){hno = a; street = s; pin=p;}
}
Student s1 = new Student("Krishna", new Address("2-2-22", "somewhere", 123), 30);
Student s2 = new Student("Krishna", new Address("1-1-11", "nowhere", 123), 20);
source
share