简体   繁体   中英

Java Trying to use a For loop to iterate through a Int ArrayList and add to a Hashset Issue

Here is the code:

public void receiveCandidates(ArrayList<Integer[]> candidates) {
    // ArrayList<Integer[]> list = new ArrayList<Integer[]>
    Set<Integer> senders = new HashSet<Integer>();
    for (Integer[] candidate : candidates) {
        // senders.add(candidate.senders);
        senders.add(candidate);
    }
    for (int i = 0; i < followees.length; i++) {
        if (followees[i] && !senders.contains(i))
            maliciousFollowees[i] = true;
    }
    for (Integer[] c : candidates) {
        if (!maliciousFollowees[c.sender]) {
            pendingTransactions.add(c.tx);
        }

}

}

My issues comes from "senders.add(cndidate);" I am not sure what I am doing wrong in the forloop. I tried wrapping it with the ArrayList but that did not work. I get an error of using .add = "error: incompatible types: Integer[] cannot be converted to Integer". The third for loop is also not working but once the first one works I am sure I can get the that to work. Any help would be greatly appreciated. I can supply the rest of the code if that helps for the third for loop if you have help for that as well.

edit: Okay so maybe this will be more clear in what I am trying to do. Originally I am trying to convert this code into what I have above. Here is the original code:

public void receiveFromFollowees(Set<Candidate> candidates) {
    Set<Integer> senders = new HashSet<>();
    for (Candidate candidate : candidates) {
        senders.add(candidate.sender);
    }
    for (int i = 0; i < followees.length; i++) {
        if (followees[i] && !senders.contains(i))
            maliciousFollowees[i] = true;
    }
    for (Candidate c : candidates) {
        if (!maliciousFollowees[c.sender]) {
            pendingTransactions.add(c.tx);
        }
    }
}

edit2: Here is the code regarding sender:

public class Candidate {
Transaction tx;
int sender;

public Candidate(Transaction tx, int sender) {
    this.tx = tx;
    this.sender = sender;
}

}

In the for-each loop you need to define a type of single item of array or collection that you are iterating:

for (Integer candidate : candidates) {

In your case this is Integer instead of Integer[] .

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