Daniel ask you a question ?
There is a list of the A collection contains a lot of objects , A object has five fields , and each field has a value object .
objects now have a B , B and A have the same object fields , but there are some fields do not have values , how to determine the list collection contains B such objects .
example List
list = new ArrayList (); A a1 = new A (); A a2 = new A (); A a3 = new A (); list.add (a1); list.add (a2); list.add (a3); B b1 = new B (); ------ Solution ------------------------------------ -------- do not know the meaning import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListHava { public static void main(String[] args) { List<Object> list = new ArrayList<Object>(); A a1 = new A(); A a2 = new A(); A a3 = new A(); list.add(a1); list.add(a2); list.add(a3); B b1 = new B(); list.add(b1); System.out.println(listHaveEqual(list, a1, b1)); } public static boolean listHaveEqual(List<Object> l, Object p, Object q) { if((l.contains(p)&&l.contains(q))==false){ return false; } Class pclass = p.getClass(); Class qclass = q.getClass(); Field[] f1 = pclass.getDeclaredFields(); Field[] f2 = qclass.getDeclaredFields(); for(int i=0;i<f1.length;i++){ f1[i].setAccessible(true); } for(int i=0;i<f2.length;i++){ f2[i].setAccessible(true); } for (Field f : f1) { System.out.println(f); String n = f.getName(); Class t = f.getType(); Boolean equal = false; for (Field ff : f2) { if (ff.getName().equals(n) && ff.getType().equals(t)) { equal = true; break; } } if (equal == false) { return false; } } return true; } } class A { int i = 1; int t = 3; boolean q = false; } class B { int i = 2; int t = 4; boolean q = true; String r = "dsfa"; } ------ Solution ------------------------------------- ------- first tests whether two objects are in the same collection inside, and then compare the object's fields , if p objects owned by all fields are q objects have ( no matter how much value ) , then return true, otherwise false ------ For reference only ------------------------------ --------- your description is not very clear , if the "B and A have the same object field ," then B and A it does not belong to the same class , but it looks like you are not following program a class. If it is not a class would be better to do, use instanceof to determine the type if (list.get (i) instanceof B) { .... } ------ For reference only --------------------------------- ------ you want to determine whether there was an object B , B and A have the same off the field what is the relationship ? ------ For reference only -------------------------------------- - +1 ------ For reference only -------------------------------- ------- instanceof B to B will be able to determine whether a ------ For reference only --------------- ------------------------ I have come to learn just help the landlord under the roof
没有评论:
发表评论