简体   繁体   中英

obtain same fields from two different classes

I have Class A and Class B

In Class AI have some fields

private String name;
private String address;
private String phoneNo;

Class BI have some fields too

private String name;
private String city;
private String phoneNo;

In my main Class I get fields from both classes

A a = new A();
B b = new B(); 
Field[] fieldsFromA = a.getClass().getDeclaredFields();
Field[] fieldsFromB = b.getClass().getDeclaredFields();

I would like to have another Field[ ] where I can store fields that both exists in Class A and B

in ths example it would be name and phoneNo

is there a simple way to do that ?

I was thinking of doing a double for loop to filter out the same fields and then add them into the array but there are cases that Class A may contain more fields than Class B or vise versa which may lead me to miss out some...

We create two variables:

A a = new A("name", "adress", "phoneNo");
B b = new B("name", "city", "phoneNo");

And get their fields:

Field[] aF = a.getClass().getFields();
Field[] bF = b.getClass().getFields();

Then:

Set<String> s1 = new HashSet<String>();
Set<String> s2 = new HashSet<String>();
List<Field> aFL = Arrays.asList(aF);
aFL.forEach(field -> {
    String temp = field.getName();
    s1.add(temp);
});
List<Field> bFL = Arrays.asList(bF);
bFL.forEach(field -> {
    String temp = field.getName();
    s2.add(temp);
});

The code above will put the names of the fields, which will be unique, into sets.

s1.retainAll(s2);

Here we get the intersection of the sets.

String[] result = s1.toArray(new String[s1.size()]);
for (String f : result) {
    System.out.println(f);
}

and then we print the output.

You can convert this to a Set and then add it a third Set.

Something like this you can do:

Set<Field> mySet1 = new HashSet<Field>(Arrays.asList(fieldsFromA));
Set<Field> mySet2 = new HashSet<Field>(Arrays.asList(fieldsFromB));
mySet2.addAll(mySet1);
// then you can convert it Array

you can use a HashSet , and put all fields in class A into set
then : as for fields in class B if it's contained in set then add it into your target array.


the pseudocode

for(File file: A){
    set.add(file);
}
for(File file: B){
    if(set.contains(file)){
        targetRes.add(file);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM