尝试计算两个不同 ArrayLists of Objects 的差异,其实例字段类型为 Integer[JAVA]

Trying to Compute the differences in two different ArrayLists of Objects with Instance Fields of Type Integer[JAVA]

提问人:Dean Loyals 提问时间:6/4/2023 最后编辑:greg-449Dean Loyals 更新时间:6/4/2023 访问量:18

问:

package pckg;

import java.util.ArrayList;
import java.util.HashMap;

public class Tester 
{
    public static void main(String[] args) 
    {
        ArrayList<TesterObj> my_first_objects = new ArrayList<TesterObj>();
        TesterObj one = new TesterObj(5,"john",6.8,"HELKEOLOSSJK NHSSB BSBSJBS NS S");
        TesterObj two = new TesterObj(25,"eric",12.32,"SKSMK skm1d dms dnms kmdks");
        TesterObj three = new TesterObj(15,"sally",2.40,"dskmdnk kmdk kwmd kdsmkd qpdok");
        TesterObj four = new TesterObj(31,"susan",9.87,"ksmdks qwersc kpaolxnio akmdn");
        TesterObj five = new TesterObj(18,"mary",86.32,"dksnd oqoijdl padxl");

        my_first_objects.add(one);
        my_first_objects.add(two);
        my_first_objects.add(three);
        my_first_objects.add(four);
        my_first_objects.add(five);

        ArrayList<TesterObj> my_second_objects = new ArrayList<TesterObj>();

        TesterObj six = new TesterObj(12,"jolly",20.4,"dxksmd oasodkx skldm");
        TesterObj seven = new TesterObj(93,"buddy",34.32,"osdk lsldm lasdkoa");
        TesterObj eight = new TesterObj(44,"kurt",90.54,"dksmd llamz kmska alsmx");
        TesterObj nine = new TesterObj(35,"jimi",923.23,"alsmx zmasx skdm akdm");
        TesterObj ten = new TesterObj(42,"kanye",12.43,"aposdkx xksmd");

        my_second_objects.add(six);
        my_second_objects.add(seven);
        my_second_objects.add(eight);
        my_second_objects.add(nine);
        my_second_objects.add(ten);

        match(my_first_objects, my_second_objects);
    }

    // OBJS_ONE and OBJS_TWO MUST BE EQUAL IN SIZE!!! , 3 is number of instance fields to compare

    public static HashMap<TesterObj,TesterObj> match(ArrayList<TesterObj> objs_one, ArrayList<TesterObj> objs_two)
    {
        ArrayList<Integer> diffs = new ArrayList<Integer>();
        HashMap<TesterObj,TesterObj> map = new HashMap<TesterObj,TesterObj>();

        for(int z=0;z<objs_one.size(); z++) 
        {
            for(int l = 0;l<objs_two.size(); l++) 
            {
                System.out.println("THE AGE OF OBJ ONE IS " + objs_one.get(z).age +
                        "THE AGE OF OBJ TWO IS " + objs_two.get(l).age );
                diffs.add(Math.abs(objs_one.get(z).age - objs_one.get(l).age));
                System.out.println(diffs);
            }
        }
        return map;
    }
}

第一次迭代(内部循环的)应该返回 7,因为它是 7,但它返回 0。此模式继续,下一次迭代在应返回时返回 10 或 88。Math.abs(5-12)Math.abs(5-93)

然后,该项目的目标是逐行继续执行此操作(每个 obj 一个迭代一次,用于 n 个 obj 两个元素),直到完成,然后返回最小的差异。

java 对象 oop 数组列表

评论


答:

0赞 Dean Loyals 6/4/2023 #1

改变 Math.abs(objs_one.get(z).age - objs_one.get(l).age 自 Math.abs(objs_one.get(z).age - objs_two.get(l).age