0

I am trying to print out attribute from two different ArrayLists in the same syso. Cant get it to work and killed myself finding out why it doesnt

    for (int i = 0; i < resultlist.size(); i++) {
        Athlete matched = null;
        Result res = resultlist.get(i);
        for (int x = 0; x < resultlist.size(); x++) {
            Athlete del = athletes.get(i);
            if (res.compStartNumber() == del.startNumber()) {
                matched = del;
                break;
            }
        }
        System.out.println(matched.surName() + " " + matched.lastName() + " has result: " + res.resultValue());
    }

Works fine just printing out the resultValue for each Result but cant get it to work with the name aswell. So my question is: What am I doing wrong?

A.Bohlund
  • 195
  • 1
  • 10
  • Show us the code that you use for the name. Possibly your problem is the issue addressed in [this thread](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Ted Hopp Jan 02 '16 at 23:36
  • Are you comparing `Strings` with `==`? – Turing85 Jan 02 '16 at 23:37
  • 2
    You iterate twice on the same list. The variable `x` is not used anywhere. – JB Nizet Jan 02 '16 at 23:38
  • You should iterate second loop with `x < athletes.size();` and use `x` on `athletes.get(x)` – Sedat Polat Jan 02 '16 at 23:42
  • 1
    In fact, you should use foreach loops, which would prevent all these bugs from occurring. And you should also use a Map instead of a list, to avoid having an O(n^2) algorithm. – JB Nizet Jan 02 '16 at 23:44

1 Answers1

2

I think you should change

for (int x = 0; x < resultlist.size(); x++) {
    Athlete del = athletes.get(i);
    ...

to

for (int x = 0; x < athletes.size(); x++) {
    Athlete del = athletes.get(x);
    ...

so as to loop through the athletes arraylist correctly, since the 2 arraylists are probably not the same size. Also, this way you would scan all the athletes for each Result.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67