Issue
I would like to get data from a CSV file. First entry is name of user, others are values. Everything works, but when I create new User object (name and bills parameters) and add it to ArrayList of Users, bills parameter of all my previous objects stored in array list are overwritten.
Main.java:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static ArrayList<Integer> bills = new ArrayList<Integer>();
private static ArrayList<User> users = new ArrayList<User>();
public static void main(String[] args) throws Exception {
//ArrayList<Integer> bills = new ArrayList<Integer>();
// System.out.println("Enter full path to csv file: ");
// String path = scanner.nextLine();
// System.out.println("Enter delimiter: ");
// String delimiter = scanner.nextLine();
scanner = new Scanner(new File("..."));
//scanner.useDelimiter(";");
// while(scanner.hasNext()) {
// System.out.print(scanner.next());
// }
int i = 0;
int bill;
while(scanner.hasNextLine()) {
i++;
bills.clear();
String line = scanner.nextLine();
String[] fields = line.split(";");
String name = fields[0];
for (String field: fields) {
try {
bill = Integer.parseInt(field);
bills.add(bill);
} catch (NumberFormatException e) {
}
}
System.out.print(name);
System.out.println(bills);
User newUser = User.createUser(name, bills);
//User newUser = new User(name, bills);
System.out.println(newUser.getName() + ">" + newUser.getBills());
users.add(newUser);
//System.out.println();
}
scanner.close();
}
public static void getMax(String userName) {
for(int i = 0; i < users.size(); i++) {
//if(users.get(i).getName().equals(userName)) {
System.out.print(users.get(i).getName());
System.out.println(users.get(i).getBills());
//}
}
}
}
User.java:
import java.util.ArrayList;
import java.util.Collections;
public class User {
private String name;
private ArrayList<Integer> bills;
public User(String name, ArrayList<Integer> bills) {
this.name = name;
this.bills = bills;
}
public String getName() {
return this.name;
}
public ArrayList<Integer> getBills() {
return this.bills;
}
public static User createUser(String name, ArrayList<Integer> bills) {
return new User(name, bills);
}
}
Solution
You are sharing the same instance of bills
in every User
.
Remove the static List for bills
and instantiate a new one with each iteration of the loop.
while(scanner.hasNextLine()) {
List<Integer> bills = new ArrayList<>();
... reading from stream happens ...
User user = new User(name, bills);
users.add(user);
}
Answered By - vsfDawg
Answer Checked By - Pedro (JavaFixing Volunteer)