简体   繁体   中英

Using getters and setters with ArrayLists in java

I'm trying to read a csv and storing the records in an ArrayList. Since I know the no. of records in the csv file I'm specifying the size ie 600 when creating the object. I want the program to be able to read files of unknown no. of records. How do I make it dynamic.

Here's the working code for the file with 600 records.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.io.*;


public class BankRecords extends Client{
//Create objects for processing data
//private static int count;
static BankRecords[] obj=new BankRecords[600];
static List<List<String>> array = new ArrayList<List<String>>();
@Override
void readData() {
    // TODO Auto-generated method stub
    String line=" ";
    //int i=0;

    //try with resources statement
    try(BufferedReader br = new BufferedReader(new FileReader("bank-Detail.csv"))){

        while((line=br.readLine()) != null) //read from file
        {   
            array.add(Arrays.asList(line.split(",")));
            //check data
            //count++;
            //System.out.println(array.get(i++));
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    processData();
}
@Override
void processData() {
    // TODO Auto-generated method stub

    int idx=0;
    for(List<String> bankData: array)
    {

        obj[idx]= new BankRecords();
        obj[idx].setId(bankData.get(0));
        obj[idx].setAge(Integer.parseInt(bankData.get(1)));
        obj[idx].setSex(bankData.get(2));
        obj[idx].setRegion(bankData.get(3));
        obj[idx].setIncome(Double.parseDouble(bankData.get(4)));
        obj[idx].setMarried(bankData.get(5));
        obj[idx].setChild(Integer.parseInt(bankData.get(6)));
        obj[idx].setCar(bankData.get(7));
        obj[idx].setSact(bankData.get(8));
        obj[idx].setCact(bankData.get(9));
        obj[idx].setMort(bankData.get(10));
        obj[idx].setPep(bankData.get(11));


        idx++;

        //System.out.println(obj[idx].getId());
        }

    printData();
}





@Override
void printData() {

    //Printing First 25 ID, age, sex, region, income and mortgage
    System.out.println("ID\t\tAGE\t\tSEX\t\tREGION\t\tINCOME\t\tMORTGAGE\n");
    for(int i=0;i<25;i++){

        String s=String.format("%s\t\t%s\t\t%s\t\t%-10s\t%8.2f\t%2s", obj[i].getId(),obj[i].getAge(),obj[i].getSex(),obj[i].getRegion(),obj[i].getIncome(),obj[i].getMort());
        System.out.println(s);
    }
}
public String getId() {
    return id;
}




public void setId(String id) {
    this.id = id;
}




public int getAge() {
    return age;
}




public void setAge(int age) {
    this.age = age;
}




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 double getIncome() {
    return income;
}




public void setIncome(double income) {
    this.income = income;
}




public String isMarried() {
    return married;
}




public void setMarried(String married) {
    this.married = married;
}




public int getChild() {
    return child;
}




public void setChild(int child) {
    this.child = child;
}




public String getCar() {
    return car;
}




public void setCar(String car) {
    this.car = car;
}




public String getSact() {
    return sact;
}




public void setSact(String sact) {
    this.sact = sact;
}




public String getCact() {
    return cact;
}




public void setCact(String cact) {
    this.cact = cact;
}




public String getMort() {
    return mort;
}




public void setMort(String mort) {
    this.mort = mort;
}




public String getPep() {
    return pep;
}




public void setPep(String pep) {
    this.pep = pep;
}




public static void main(String[] args) {
    // TODO Auto-generated method stub
    BankRecords bnk= new BankRecords();
    bnk.readData();
}

}

You do not have to know the number of records beforehand in order to use an ArrayList . You can specify a default size in the constructor, however it is smart enough to expand itself if you add more records than this.

ArrayList can the elements dynamically, so it is not required to know the size in advance.

However, for the BankRecords array, do not initialize it with 600 initially. Instead do something like this:

static BankRecords[] obj = null;
static List<List<String>> array = new ArrayList<List<String>>();
void processData() {
    // TODO Auto-generated method stub
    obj=new BankRecords[array.size()];
    // TODO do your work here 
}

You are almost there, but for some strange reasons you are using Lists in places where you already have an array; yet on the other side, you are using an array where a List would be a much better fit.

You can rework your code as follows:

// TODO Auto-generated method stub

HINT: those TODOs are generated by your IDE. The idea is that you delete them as soon as you have some real content instead. Keeping them means leaving garbage in your source code. Anything that doesn't add real value to your source code: remove it. Always. Immediately!

String line=" ";
List<Bankrecord> records = new ArrayList<>();
//int i=0; ... again: unused code --- remove that!
try(BufferedReader br = new BufferedReader(new FileReader("bank-Detail.csv"))){
    while((line=br.readLine()) != null) //read from file
    {   
      String[] lineData = line.split(",");
      BankRecord recordForNewLine = buildRecordFrom(lineData);
      records.add(recordForNewLine);
    } ...

And then you could rework your processData into something like:

private BankRecord buildRecordFrom(String[] lineData) {
  BankRecord newRecord = new BankRecords();
  newRecord.setId(lineData[0];
  ...
  return newRecord;
}

And things that you should really consider changing, too:

  • Building your bank records by simply assuming that column contains a valid ID, and the next column contains a valid xyz ... is a bad idea.
  • Instead, you should be validating all your input: you should check that each array you gain from split has **exactly the expected length. And then have to validate that each value from that array has the expected "content"
  • Then, from a modelling perspective: you have a ton of setters on your Bankrecord class. But that is simply wrong! In real life, when some "record" is created, then its essential properties (such as its ID) can't be changed after creation!
  • Instead, you should make sure that such properties in your class can't be changed after the object has been created. The way to go here: Builder pattern !

Finally: my code above is meant as "inspiration point" to get you going. Dont blindly copy/paste it; there might be various typos in - just read it until you get what (and why) it is doing (what it is doing)!

Then: I hope you understand that real CSV parsing is much more complicated than splitting around "," (for example: strings in CSV data can contain ',' too; and then your simple split would rip up that string!) If you are serious about parsing real-world-other-people CSV input, then you better look into using existing libraries to do this for you. Writing a correct CSV parser is hard work (and not very rewarding; since that means re-inventing a complicated wheel for no good reason)!

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