如何在不手动输入的情况下在ArrayList中创建具有相同内容的多个对象?

时间:2018-11-21 06:31:06

标签: java object arraylist

这是我的示例代码,在“用户列表”中,内部有10个用户,其中一半具有相同的价值。我想问一下如何做到这一点,而无需手动输入就可以生成重复对象的一半?

--User Class--

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class User {
     private String firstName;
     private String lastName;
     private int age;



public User(String firstName,String lastName, int age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}


    /**
 * @return the firstName
 */
public String getFirstName() {
    return firstName;
}
/**
 * @param firstName the firstName to set
 */
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
/**
 * @return the lastName
 */
public String getLastName() {
    return lastName;
}
/**
 * @param lastName the lastName to set
 */
public void setLastName(String lastName) {
    this.lastName = lastName;
}
/**
 * @return the age
 */
public int getAge() {
    return age;
}
/**
 * @param age the age to set
 */
public void setAge(int age) {
    this.age = age;
}


}

这是主班。

--Main Class--

import java.util.ArrayList;
import java.util.List;

public class Main {

public static void main(String[] args) {

    List<User> users= new ArrayList<>();
    users.add(new User("James", "Lim", 24));
    users.add(new User("James", "Lim", 24));
    users.add(new User("James", "Lim", 24));
    users.add(new User("James", "Lim", 24));
    users.add(new User("James", "Lim", 24));
    users.add(new User("David", "So", 20));
    users.add(new User("Rowan", "Yeo", 21));
    users.add(new User("Joshua", "Low", 23));
    users.add(new User("Jackson", "Lim", 21));
    users.add(new User("Daniel", "Fo", 21));

     users.forEach(user -> {
            System.out.println(user.getFirstName() + "," + user.getLastName());
     });
}

我该如何做才能允许生成列表中所有用户的1/2个重复用户而无需手动输入?

1 个答案:

答案 0 :(得分:1)

为什么不使用这样的for循环?

List<User> users= new ArrayList<>();
for (int i = 0; i < 5; i++) {
    users.add(new User("James", "Lim", 24));
}

或者,当有很多重复项时,您可以使用类似的方法来添加用户

private static void addUsers(List<User> users, int count, User user) {
    for (int i = 0; i < count; i++) {
        users.add(user);
    }
}

public static void main(String[] args) {
    List<User> users = new ArrayList<>();
    addUsers(users, 5, new User("David", "So", 20));
}