简体   繁体   中英

why is my method returning wrong results

I have a test:

    public void testGetUniqueResults(){
APRecord p1 = new APRecord();
p1.settId("l1");
APRecord p2 = new APRecord();
p2.setId("l2");
APRecord p3 = new APRecord();
p3.setId("l1");
APRecord p4 = new APRecord();
p4.setId("l4");
List< APRecord > listPatch = new ArrayList< APRecord >();
listPatch.add(p1);
listPatch.add(p2);
listPatch.add(p3);
listPatch.add(p4);

List<ARecord> recs = new ArrayList<ARecord>();
recs.addAll(listPatch);
unique(recs);
System.out.println("records" + recs); //return all the 4 results whereas it should return 3



}

and a method:

    public List<ARecord> unique(List<Record> list) {
    System.out.println(list);

    HashMap<String, ARecord > uniqueRecs = new HashMap<String, ARecord >();

    for(ARecord records:list){
        if(!uniqueRecs.containsKey(records.getId())){
            uniqueRecs.put(records.getId(), records);
        }
    }
    List< ARecord > finalRecs = new ArrayList< ARecord>(uniqueRecs.values());
    for(ARecord record:finalRecs){
        System.out.println("records final in method "+record);
    }


    return finalRecs; //returns correct result
}

My finalRecs in method unique returns the expected results but when I pass recs to my unique list, it returns all my results whereas I'm expecting three results but I get all four even though my method unique returns 3 results. Where am I doing wrong? any help appreciated.

The reason you are seeing 4 results is that you never use the return value from your method unique() . And you also do not operate on the input List which you pass in, so the effort in your method is currently for naught. Here is where your code currently stands:

List<ARecord> recs = new ArrayList<ARecord>();
recs.addAll(listPatch);
unique(recs);           // you never use the return value!

Replace this code with the following and all should be good:

List<ARecord> recs = new ArrayList<ARecord>();
recs.addAll(listPatch);
recs = unique(recs);    // you should be fine now

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