HashSet equals, hashCode are overriden, styl have duplicates - java

public class DateObj extends Date implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String fName;
private String sName;
private String days;
private String country;
private boolean fitIn;
public DateObj(String id,String fName, String sName, String country, String days) {
this.id = id;
this.fName = fName;
this.sName = sName;
this.days = days;
this.country = country;
}
#Override
public boolean equals(Object obj) {
DateObj dateObj = (DateObj) obj;
System.out.println("method Call");
return getfName().equals(dateObj.getfName());
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String toString(){
return fName;
}
#Override
public int hashCode() {
return fName.hashCode();
}
}
==========================================================================================
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
public class DataSaveTo {
private ArrayList<DateObj> listData = new ArrayList<DateObj>();
File file = new File("data3.csv");
public static void main(String[] args) {
DataSaveTo dataExperiment = new DataSaveTo();
dataExperiment.go();
}
public void go() {
loadData();
TreeSet<DateObj> data = new TreeSet<DateObj>();
data.addAll(listData);
// ObjComparInt comparId = new ObjComparInt();
// ObjectComparable comparObj = new ObjectComparable();
// Collections.sort(listData, comparId);
saveData();
// System.out.println(listData);
}
public void saveData() {
try {
File file = new File("dataNoDupl.csv");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for(DateObj obj : listData){
bw.write(obj.getId()+";"+obj.getfName()+";"+obj.getsName()+";"+obj.getCountry()+";"+obj.getDays()+"\n ");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception in save Data method: "+ e);
}
}
public void loadData() {
FileReader fr;
try {
fr = new FileReader(file);
String s = null;
String[] tokens;
BufferedReader br = new BufferedReader(fr);
while((s=br.readLine())!=null){
tokens = s.split(",");
createDateObj(tokens);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("Exception in LoadData method"+e);
} catch (IOException e) {
System.out.println("Exception in LoadData method 2nd catch"+e);
e.printStackTrace();
}
}
private void createDateObj(String[] tokens) {
DateObj obj = new DateObj(tokens[4],tokens[0],tokens[2],tokens[3],tokens[1]);
listData.add(obj);
System.out.println(obj.hashCode()+"--"+obj.getfName()+"--"+obj.getsName());
}
// Name comparator
public class ObjectComparable implements Comparator<DateObj>{
#Override
public int compare(DateObj obj, DateObj obj1) {
return obj.getfName().compareTo(obj1.getfName());
}
}
// ID comparator
public class ObjComparInt implements Comparator<DateObj>{
#Override
public int compare(DateObj ob, DateObj ob1){
return Integer.parseInt(ob.getId()) - Integer.parseInt(ob1.getId());
}
}
}
I want HashSet to call equal method, because of overriden hashCode. And after equals compare,I want to remove duplicates in mine Collection I am passing into the hashSet.
HashSet<DateObj> data = new HashSet<DateObj>();
data.addAll(listData);
In console it prints me out, true (because of sys.out in equals method) but it does not do anything. I styl have duplicates.

With having same fName does not get same hash Value. As you consider sName also while generating hash code.
When you are putting the objects into your HashSet, hash code is generated and your hash code implementation generates hash code according to your fName and sName. On the other hand you are matching only fName in your equal method and get true printed!
First Define when you want to consider your objects same. Use those criteria to match in equals method and also consider them in hashCode method also. Because if two objects are equal, their hash code must to be equal!

The Java documentation of hashCode() states that:
If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce
the same integer result.
Your implementation is breaking this rule, and you need to change either the implementation of hashCode() or equals() to fulfill it.
You probably want to update equals():
#Override
public boolean equals(Object obj){
if (obj == null || !(obj instanceof DateObj)) {
return false;
}
DateObj dateObj = (DateObj) obj;
return getfName().equals(dateObj.getfName()) && getsName().equals(dateObj.getsName());
}

Related

Java: Arraylist out of bounds when processing file [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am trying to create an ArrayList that reads a .csv file, processes the data into an ArrayList, and then print the list out.
My code so far.
The BankRecords class
import java.io.*;
import java.util.*;
public class BankRecords
{
String sex, region, married, save_act, current_act, mortgage, pep;
int children;
double income;
private String id;
private int age;
public BankRecords(String gender, String area, String marriage, String SaveAccount, String CurrentAccount, String HouseBill, String pepp, int minors, double paycheck, String identification, int years)
{
this.sex = gender;
this.region = area;
this.married = marriage;
this.save_act = SaveAccount;
this.current_act = CurrentAccount;
this.mortgage = HouseBill;
this.pep = pepp;
this.children = minors;
this.income = paycheck;
this.id = identification;
this.age = years;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getRegion()
{
return region;
}
public void setRegion(String region)
{
this.region = region;
}
public String getMarried()
{
return married;
}
public void setMarried(String married)
{
this.married = married;
}
public String getSave_act()
{
return save_act;
}
public void setSave_act(String save_act)
{
this.save_act = save_act;
}
public String getCurrent_act()
{
return current_act;
}
public void setCurrent_act(String current_act)
{
this.current_act = current_act;
}
public String getMortgage()
{
return mortgage;
}
public void setMortgage(String mortgage)
{
this.mortgage = mortgage;
}
public String getPep()
{
return pep;
}
public void setPep(String pep)
{
this.pep = pep;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getChildren()
{
return children;
}
public void setChildren(int children)
{
this.children = children;
}
public double getIncome()
{
return income;
}
public void setIncome(double income)
{
this.income = income;
}
}
The Client abstract class
import java.io.*;
import java.util.*;
public abstract class Client
{
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
static BankRecords robjs[] = new BankRecords[600];
public static void readData()
{
try
{
BufferedReader br;
String filepath = "C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv";
br = new BufferedReader(new FileReader (new File(filepath)));
String line;
while ((line = br.readLine()) != null)
{
BankArray.add(Arrays.asList(line.split(",")));
}
}
catch (Exception e)
{
e.printStackTrace();
}
processData();
}
public static void processData()
{
int idx=0;
for (List<String> rowData: BankArray)
{
robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
robjs[idx].setId(rowData.get(0));
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
idx++;
}
printData();
}
public static void printData()
{
System.out.println("ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE");
int final_record = 24;
for (int i = 0; i < final_record; i++)
{
System.out.println(BankArray.get(i) + "\t ");
}
}
}
The BankRecordsTest class (extends Client)
import java.util.*;
import java.io.*;
public class BankRecordsTest extends Client
{
public static void main(String args [])
{
readData();
}
}
The error
And here is the error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at java.util.Arrays$ArrayList.get(Unknown Source)
at Client.processData(Client.java:33)
at Client.readData(Client.java:24)
at BankRecordsTest.main(BankRecordsTest.java:7)
I'm not sure what the index problem is. Do note that if you run the ReadData() and PrintData() functions separately, the code runs fine but the ProcessData() method causes issues.
I think your data is likely not clean and you are making assumptions about the length of your array. The error you are getting stems from this line:
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
Clearly, rowData doesn't have 2 items (or more). This is why you are getting ArrayIndexOutOfBoundsException. So you want to check where your variable was initialized. You quickly realize it comes from
for (List<String> rowData: BankArray)
So then, the following question is where BankArray gets initialized. That happens in 2 places. First of all
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
You are creating an empty list. So far so good. Note that you don't need to (and therefore shouldn't) initialize with a size. Lists are not like arrays insofar as they can easily grow and you don't need to give their size upfront.
The second place is
BankArray.add(Arrays.asList(line.split(",")));
This is likely where the issue comes from. Your row variable contains the results of Arrays.asList(line.split(",")). So the size of that list depends on the number of commas in that string you are reading. If you don't have any commas, then the size will be 1 (the value of the string itself). And that's what leads me to concluding you have a data quality issue.
What you should really do is add a check in your for (List<String> rowData: BankArray) loop. If for instance, you expect 2 fields, you could write something along the lines of:
if (rowData.size()<2){
throw new Exception("hmmm there's been a kerfuffle');
}
HTH

how to sort a list of strings alphabetically in java?

Hie.
I am a Java beginner. I need to sort a String of names alphabetically.
i have a class that reads from a text file and writes the sorted file which filters by age(less than 18) but i need it to filter alphabetically, below is my implementation. Its working fine without filter by name.
public class PatientFileProcessor {
public void process(File source, File target) {
System.out.println("source"+source.getAbsolutePath());
System.out.println("target"+target.getAbsolutePath());
try {
writefile(target, filterbyAge(readfile(source)));
} catch (Exception ex) {
Logger.getLogger(PatientFileProcessor.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<Patient> readfile(File source) throws Exception {
List<Patient> patients = new ArrayList();
BufferedReader bf = new BufferedReader(new FileReader(source));
String s = bf.readLine();// ignore first line
while ((s = bf.readLine()) != null) {
String[] split = s.split("\\|");
System.out.println(Arrays.toString(split));
System.out.println(s+" "+split[0]+" "+split[1]+" "+split[2]);
Date d = new SimpleDateFormat("yyyy-dd-MM").parse(split[2]);
patients.add(new Patient(split[0], split[1], d));
}
return patients;
}
public void writefile(File target, List<Patient> sorted) throws Exception {
BufferedWriter pw = new BufferedWriter(new FileWriter(target));
DateFormat df = new SimpleDateFormat("yyyy/dd/MM");
for (Iterator<Patient> it = sorted.iterator(); it.hasNext();) {
Patient p = it.next();
pw.append(p.getName() + "|" + p.getGender() + "|" + df.format(p.getDob()));
pw.newLine();
}
pw.flush();
}
public List<Patient> filterbyAge(List<Patient> ps) {
List<Patient> sorted = new ArrayList();
for (Iterator<Patient> it = ps.iterator(); it.hasNext();) {
Patient s = it.next();
if (calcAge(s.getDob()) > 18) {
sorted.add(s);
}
}
return sorted;
}
public int calcAge(Date d) {
Date today = new Date();
long m = today.getTime() - d.getTime();
return (int) (m / (1000 * 60 * 60 * 24 * 365.25));
}
}
Patient:
import java.util.Date;
public class Patient {
private String name;
private String gender;
private Date dob;
public Patient() {
}
public Patient(String name, String gender, Date dob) {
this.name = name;
this.gender = gender;
this.dob = dob;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDob() {
return dob;
}
}
how do i go about it?
Assuming that those are Strings, use the convenient static method sort…
java.util.Collections.sort(patients)
For Strings this would work:
arrayList.sort((p1, p2) -> p1.compareTo(p2)); (Java 8)
What you can do is you can implement the Comparable interface in your Patient and override the compareTo method. In that way, when the sort method of Collections is called, it will use the your compareTo method for comparison.

Serializing an object to file creates blank object in file

I am trying to create an object that is then serialized and written to file but regardless of what I try, a blank object is always written to file instead.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class FileIO implements Serializable {
private static final long serialVersionUID = 1L;
private VIAModel viaModel1;
private VIAView viaView1 = new VIAView();
private VIAController viaContr = new VIAController();
public void setVIAModelFromFile() throws IOException, ClassNotFoundException, EOFException {
boolean endOfFile = false;
FileInputStream fstream = new FileInputStream("viaModel.ser");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
while (!endOfFile) {
try {
viaModel1 = (VIAModel) inputFile.readObject();
} catch (EOFException eof) {
endOfFile = true;
}
}
inputFile.close();
}
public void setToFile() throws IOException {
viaContr = viaView1.getController();
viaModel1.setEventList(viaContr.getVIAMod().getEventList());
System.out.println(viaModel1.getEventList().getListOfEvents());
FileOutputStream fstream = new FileOutputStream("viaModel.ser");
ObjectOutputStream outputFile = new ObjectOutputStream(fstream);
try {
outputFile.writeObject(viaModel1);
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException ioe) {
System.out.println("Error.");
ioe.printStackTrace();
}
}
public VIAModel getVIAModel() {
return viaModel1;
}
public void setVIAModel(VIAModel viamod) {
this.viaModel1 = viamod;
}
}
The object being written has serializable on all objects inside and objects unable to be serialized have been manually serialized. The system.out.print shows the object with the information entered in the program, but this information doesn't appear in the .ser file at all and so only a blank object is read later.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javafx.beans.property.SimpleStringProperty;
public class Events implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5596571541918537611L;
private transient SimpleStringProperty name = new SimpleStringProperty("");
private transient SimpleStringProperty date = new SimpleStringProperty("");
private transient SimpleStringProperty duration = new SimpleStringProperty("");
private transient SimpleStringProperty type = new SimpleStringProperty("");
private transient SimpleStringProperty location = new SimpleStringProperty("");
private transient SimpleStringProperty category = new SimpleStringProperty("");
// private Lecturer conductor;
private transient SimpleStringProperty price = new SimpleStringProperty("");
private transient SimpleStringProperty minPartic = new SimpleStringProperty("");
private transient SimpleStringProperty maxPartic = new SimpleStringProperty("");
private boolean isFinalized = false;
// ArrayList<Members> eventMembList = new ArrayList<>();
public Events(String name, String date, String duration, String type, String location, String category,
/* Lecturer conductor, */ String price, String minPartic, String maxPartic, boolean isFinalized) {
setName(name);
setDate(date);
setDuration(duration);
setType(type);
setLocation(location);
setCategory(category);
setPrice(price);
setMinPartic(minPartic);
setMaxPartic(maxPartic);
this.isFinalized = isFinalized;
}
public Events() {
this("","","","","","","","","",false);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getDate() {
return date.get();
}
public void setDate(String date) {
this.date.set(date);
}
public String getDuration() {
return duration.get();
}
public void setDuration(String duration) {
this.duration.set(duration);
}
public String getType() {
return type.get();
}
public void setType(String type) {
this.type.set(type);
}
public String getLocation() {
return location.get();
}
public void setLocation(String location) {
this.location.set(location);
}
public String getCategory() {
return category.get();
}
public void setCategory(String category) {
this.category.set(category);
}
public String getPrice() {
return price.get();
}
public void setPrice(String price) {
this.price.set(price);
}
public String getMinPartic() {
return minPartic.get();
}
public void setMinPartic(String minPartic) {
this.minPartic.set(minPartic);
}
public String getMaxPartic() {
return maxPartic.get();
}
public void setMaxPartic(String maxPartic) {
this.maxPartic.set(maxPartic);
}
public boolean isFinalized() {
return isFinalized;
}
public void setFinalized(boolean isFinalized) {
this.isFinalized = isFinalized;
}
public void finalizeEvent() {
this.isFinalized = true;
}
// public void addMemToEvent(Members member) {
// eventMembList.add(member);
// }
public String toString() {
return this.name + "\n" + this.date+ "\n" + this.duration+ "\n" + this.type+ "\n" + this.location+ "\n" + this.category+ "\n" + this.price+ "\n" + this.minPartic+ "\n" + this.maxPartic+ "\n" + this.isFinalized;
}
public void readExternal(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
name = new SimpleStringProperty((String) in.readObject());
date = new SimpleStringProperty((String) in.readObject());
duration = new SimpleStringProperty((String) in.readObject());
type = new SimpleStringProperty((String) in.readObject());
location = new SimpleStringProperty((String) in.readObject());
category = new SimpleStringProperty((String) in.readObject());
price = new SimpleStringProperty((String) in.readObject());
minPartic = new SimpleStringProperty((String) in.readObject());
maxPartic = new SimpleStringProperty((String) in.readObject());
}
public void writeExternal(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(name.get());
out.writeObject(date.get());
out.writeObject(duration.get());
out.writeObject(type.get());
out.writeObject(location.get());
out.writeObject(category.get());
out.writeObject(price.get());
out.writeObject(minPartic.get());
out.writeObject(maxPartic.get());
}
}
Changing SimpleStringProperty to String seems to work perfectly and eliminates all of the issues involved with serializing, which is something that I don't have the knowledge to correct.
in your below code you will end up reading only the last object make sure you are reading correct contents from input file. Did you tried populating a new VIAModel object and then writing it to the file
while (!endOfFile) {
try {
viaModel1 = (VIAModel) inputFile.readObject();
} catch (EOFException eof) {
endOfFile = true;
}
It is exactly as I said. You have
public class Events implements Serializable
and a whole series of transient fields, and also
public void readExternal(ObjectInputStream in)
and
public void writeExternal(ObjectOutputStream out)
These methods are never called. There is nothing in the Object Serialization Specification about either of these method signatures.
If you want this class to be serialized, you need to either remove transient throughout, if SimpleStringProperty is Serializable, and remove these methods, or make it extends Externalizable, and fix the resulting compilation errors.
What you can't do is just make up your own semantics and signatures and then wonder why Java doesn't implement them.

XMLEncoder not writing object data when class fields are private

I have a class with private fields and public methods. My methods follow the get/set naming convention. When my fields are private and I try to write my object data to an XML file, I get an empty XML file, but when I change them to public, the XML contains all the necessary data. What do you think is causing this?
public class ClassData {
private String name;
private ArrayList<String> methods;
public ClassData()
{
methods = new ArrayList<>();
}
public void setName(String cName)
{
name = cName;
}
public String getName()
{
return name;
}
public void setMethods(String mName)
{
methods.add(mName);
}
public ArrayList<String> getMethods()
{
return methods;
}
}
String fileName = cObj.getName() + ".xml";
XMLEncoder enc=null;
try{
enc=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
}catch(FileNotFoundException fileNotFound){
System.out.println("Unable to save file.");
}
enc.writeObject(cObj);
enc.close();
This is because your methods do not have a "Setter" to make it an accessible "property". Change method setMethods(String mName) to addMethod(String mName) to add individual method and add a setter setMethods that sets same time as that of methods and things work. Sample below:
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
public class ClassData {
private String name;
private ArrayList<String> methods;
public ClassData() {
methods = new ArrayList<>();
}
public void setName(String cName) {
name = cName;
}
public String getName() {
return name;
}
public void addMethod(String mName) {
methods.add(mName);
}
public void setMethods(ArrayList<String> m)
{
methods.addAll(m);
}
public ArrayList<String> getMethods() {
return methods;
}
public static void main(String[] args) {
ClassData cObj = new ClassData();
cObj.setName("This_is_name");
cObj.addMethod("m1");
String fileName = cObj.getName() + ".xml";
XMLEncoder enc = null;
try {
enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
} catch (FileNotFoundException fileNotFound) {
System.out.println("Unable to save file.");
}
enc.writeObject(cObj);
enc.close();
}
}

Java - Type Mismatch: Cannot Convert From Element type String[] to List<String>

I'm unfamiliar with getters and setters (and basically just Java) but I have to use them for this assignment, so if I did anything wrong with those please tell me.
The more important issue is the error that I am getting on my method. The word for word instructions from my assignment for the particular method I'm working on are:
Your processData() method should take all the record data from your ArrayList and add the data into each of your instance fields via your setters.
But I keep getting an error that says:
Type mismatch: cannot convert from element type String[] to List
On the line that says "for (List<String> rowData: content)" on the word content.
Thank you very much for any help you can give me.
My code so far:
public abstract class Client {
String file = "bank-Detail.csv";
ArrayList<String[]> bank = new ArrayList<>();
static Client o[] = new Client[12];
public Client(String file) {
this.file = file;
}
private String ID;
private String Age;
private String Sex;
private String Region;
private String Income;
private String Married;
private String Children;
private String Car;
private String Save_Act;
private String Current_Act;
private String Mortgage;
private String Pep;
public List<String[]> readData() throws IOException {
//initialize variable
int count = 0;
//name file
String file = "bank-Detail.txt";
//make array list
List<String[]> content = new ArrayList<>();
//trycatch for exceptions
try {
//file reader
BufferedReader br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
while ((line = br.readLine()) != null) {
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
processData(content);
return content;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
this.Age = age;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getRegion() {
return Region;
}
public void setRegion(String region) {
Region = region;
}
public String getIncome() {
return Income;
}
public void setIncome(String income) {
Income = income;
}
public String getMarried() {
return Married;
}
public void setMarried(String married) {
Married = married;
}
public String getChildren() {
return Children;
}
public void setChildren(String children) {
Children = children;
}
public String getCar() {
return Car;
}
public void setCar(String car) {
Car = car;
}
public String getSave_Act() {
return Save_Act;
}
public void setSave_Act(String save_Act) {
Save_Act = save_Act;
}
public String getCurrent_Act() {
return Current_Act;
}
public void setCurrent_Act(String current_Act) {
this.Current_Act = current_Act;
}
public String getMortgage() {
return Mortgage;
}
public void setMortgage(String mortgage) {
this.Mortgage = mortgage;
}
public String getPep() {
return Pep;
}
public void setPep(String pep) {
Pep = pep;
}
public String toString() {
return "[ID = " + ", age=";
/// ect....
}
public void processData(List<String[]> content) {
int index = 0;
for (List<String> rowData : content) {
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData.get(0));
o[index].setAge(rowData.get(1));
o[index].setRegion(rowData.get(3));
o[index].setSex(rowData.get(2));
o[index].setIncome(rowData.get(4));
o[index].setMarried(rowData.get(5));
o[index].setChildren(rowData.get(6));
o[index].setCar(rowData.get(7));
o[index].setSave_Act(rowData.get(8));
o[index].setCurrent_Act(rowData.get(9));
o[index].setMortgage(rowData.get(10));
o[index].setPep(rowData.get(11));
System.out.println(rowData);
index++;
}
}
public void printData() {
}
}
The problem is in the processData method. The type of content is List<String[]>. So when you try to loop this list, each element is a String array, not List. Also, since each element in your list is a String array, you can access the elements of each of the String Array elements of the list by using the normal array square brackets, instead of get method of List. Try the following fix:
public void processData(List<String[]> content) {
int index=0;
for (String[] rowData: content){
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData[0]);
o[index].setAge(rowData[1]);
o[index].setRegion(rowData[3]);
o[index].setSex(rowData[2]);
o[index].setIncome(rowData[4]);
o[index].setMarried(rowData[5]);
o[index].setChildren(rowData[6]);
o[index].setCar(rowData[7]);
o[index].setSave_Act(rowData[8]);
o[index].setCurrent_Act(rowData[9]);
o[index].setMortgage(rowData[10]);
o[index].setPep(rowData[11]);
System.out.println(rowData);
index++;
}
}
As your error hints at... content is a List<String[]>, so it contains String[] elements, not List<String> elements.
If your end goal is a list of Client objects, just make the method List<Client> readData() instead.
List<Client> clients = new ArrayList<Client>();
BufferedReader br = null;
try {
//file reader
br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
Client c = null;
while ((line = br.readLine()) != null) {
c = new Client();
String[] rowData = line.split(",");
c.setID(rowData.get(0));
...
clients.add(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (Exception e) {}
}
return clients;

Categories