简体   繁体   中英

Print this HashCode from ArrayList in Java

Going through the list of existing users is determined whether there is a same ID in the list of users who are added. If there is, this user will be deleted from the list of existing ones.

Question is: if I do this I got HashCode printed, if I put just (i) l got index printed. How to Array.toString(i) this? There is always errors.

    for (int i = 0; i < users.size(); i++) {
        for (int u = 0; u < usersToAdd.size(); u++) {
            if (((User) users.get(i)).Id == ((User) usersToAdd.get(u)).Id)
                users.remove(u);
        }
    }

    users.addAll(usersToAdd);

    for (int i = 0; i < users.size(); i++) { 

        System.out.println(users.get(i)); // how to print them ?
    }

You should normally override toString() method of the User class and then print users like this:

class User {
    private String name;

    public String toString() {
        return "User: " + name;
    }
}

List<User> users = new ArrayList<>();
...
for (User user : users) {
    System.out.println(user);
}

If you really have to have collection of Objects (I would not recommend this):

for (Object user : users) {
    System.out.println(user);
}

UPD: without toString() method you can just:

for (User user : users) {
    System.out.println("User: " + user.getName() + user.getId());
}

You should override the toString() method:

public class User { 

    public int Id; 
    public String ime; 

    public User(int id, String ime) { 
        this.Id = id; 
        this.ime = ime; 
    } 

    public String toString() {
        return "Id: " + Id + ", ime: " + ime;
    }

}

and use id instead of Id .

User class should override toString method, since the default implementation of it is the hash code:

public class User { 
    public int Id; 
    public String ime; 

    public User(int id, String ime) { 
        this.Id = id; this.ime = ime; 
    }

    @Override
    public String toString() {
        return "Id: " + Id + ", Ime: " + ime;
    }

}

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