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
Related
I am creating a lobby application which will show all groups on a java tableview. Users are able to join groups that have space in them, else they will not be able to join.
I have been able to create this but I would like to be able to colour the row of the groups that have space in them in green and groups that are full will be coloured in red.
I will provide my code for this below. I am getting NullPointerException, which i dont know why. Thanks.
private void visualGroupAvailability() {
boolean isThereSpace;
for (currentGroupsModel o : groupsTable.getItems()) {
TableRow<currentGroupsModel> currentRow = getTableRow(o.getGroupID());
int limit = o.getNumberOfUsers();
isThereSpace = checkSpaceInGroup(o);
if(isThereSpace) {
currentRow.setStyle("-fx-background-color: #" + "388e3c ");
} else {
currentRow.setStyle("-fx-background-color: #" + "ffcdd2 ");
}
}
}
private TableRow<currentGroupsModel> getTableRow(int rowIndex) {
Set<Node> tableRowCell = groupsTable.lookupAll(".table-row-cell");
TableRow<currentGroupsModel> row = null;
for (Node tableRow : tableRowCell) {
TableRow<currentGroupsModel> r = (TableRow<currentGroupsModel>) tableRow;
row = r;
}
return row;
}
public class currentGroupsModel {
String groupName, groupDescription, hostName, groupType;
Integer numberOfUsers, groupID;
public currentGroupsModel(String gName, String gDesc, String hostName, String groupType, Integer numberOfUsers, Integer groupID){
this.groupName = gName;
this.groupDescription = gDesc;
this.hostName = hostName;
this.groupType = groupType;
this.numberOfUsers = numberOfUsers;
this.groupID = groupID;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupDescription() {
return groupDescription;
}
public void setGroupDescription(String groupDescription) {
this.groupDescription = groupDescription;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getGroupType() {
return groupType;
}
public void setGroupType(String groupType) {
this.groupType = groupType;
}
public Integer getNumberOfUsers() {
return numberOfUsers;
}
public void setNumberOfUsers(int numberOfUsers) {
this.numberOfUsers = numberOfUsers;
}
public Integer getGroupID(){
return this.groupID;
}
public void setGroupID(Integer newID){
this.groupID = newID;
}
}
This question cannot really be answered with what you have given us. It is hard looking for a NullPointerException if there is a currentGroupModel we know nothing about and there are constant red hairings. For example why do you store something in limit, you never use it! Why do you pass getTableRow a rowIndex, that you are never using? As far as I get it your getTableRow returns the last TableRow in the table, not a specific one. Please consider fixing those problems first, before eventually providing some code to understand the inner workings of your currentGroupModel.
I have a Contact class that basically just holds information of a contact. We store the contact object in an array.
I had to write the array into a text file, and I knew how to do that, but now I must read that file and store the objects back into an array, and I'm stuck!
Note, ContactList Below also uses class Contact, which just basically has get/set methods.
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
public class ContactList{
int ptr = -1;
Contact[] list;
int contactLength;
public ContactList(){//second constructor needed
list=new Contact[20];
contactLength=20;
for(int i =0;i<20;i++){
list[i]=null;
}
}
public ContactList(int length){//second constructor needed
list=new Contact[length];
contactLength=length;
for(int i =0;i<length;i++){
list[i]=null;
}
}
public boolean add(Contact c){
boolean found = false;
int i = 0;
while(!found&&i<20){
if (list[i]==null){
list[i]=c;
found=true;
ptr=i;
}
i++;
}
return found;
}
public Contact find(String name){
boolean found=false;
int i =0;
while(i<contactLength&&!found){
ptr++;
if(ptr==contactLength){
ptr=0;
}
if(list[ptr]!=null){
if (list[ptr].getName().contains(name)){
found=true;
return list[ptr];
}
}
i++;
}
return null;
}
public Contact remove(){
Contact current= list[ptr];
list[ptr]=null;
return current;
}
public void displayContacts(){
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
System.out.println(list[i].toString());
}
else {
System.out.println("Empty:");//"Name:\nAddress:\nPhone\nComments:"
}
}
}
public boolean write (String fileName){
PrintWriter p = null;
try {
p = new PrintWriter(new File(fileName));
} catch (Exception e) {
return false;
}
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
p.println(list[i].toString());
}}
p.close();
return true;
}
public class Contact {
private String name;
private long phone;
private String address;
private String comments;
public void setName( String name){
this.name =name;
}
public String getName(){
return name;
}
public void setPhone(long phone){
this.phone=phone;
}
public long getPhone(){
return phone;
}
public void setAddress(String address){
this.address= address;
}
public String getAddress(){
return address;
}
public void setComments( String comments){
this.comments= comments;
}
public String getComments(){
return comments;
}
public String toString(){
return ("Name:\t\t"+name+"\nAddress:\t"+address+"\nPhone Number:\t"+phone+"\nComments:\t"+comments +"\n");
}
public Contact(String name, long phone, String address, String comments){
this.name=name;
this.phone=phone;
this.address=address;
this.comments=comments;
}
public boolean equals(Contact other){
if (this.name!=other.name){
return false;
}
if (this.phone!=other.phone){
return false;
}
if (this.address!=other.address){
return false;
}
if (this.comments!=other.comments){
return false;
}
return true;
}
Here is what I have so far...
public boolean read(String fileName){
Scanner s = null;
try {
s = new Scanner(new File(fileName));
} catch (Exception e) { // returns false if fails to find fileName
return false;
}
for(int i=0; i)
}
And YES I must use array! No lists! And nothing fancy please, this is an intro class, I won't understand it. Just scanner.
I see the pros and cons in the comment section, what about putting an end to the debate, given how you write I'm guessing you will need something like:
public static void read(String fileName){
try(BufferedReader in = new BufferedReader(new FileReader(fileName))){
String line = null;
String[] contact = new String[4];
int contactCounter = 0;
int buffer = 0;
while ((line = in.readLine()) != null){
buffer = line.split("\t").length - 1;
contact[contactCounter] = line.split("\t")[buffer];
contactCounter++;
if (contactCounter == 3){
new Contact(contact[0], contact[1], contact[2], contact[3]);
contactCounter == 0;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
I strongly suggest you improve how you serialize your Contact because this format is a mess, especially having not clear boundaries, the best I could figure was counting 4 EOL to create a new Contact.
Maybe have a look at csv format: https://en.wikipedia.org/wiki/Comma-separated_values
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;
I have to parse the json file into text file, Sample json file as below,
{
"link":"https://xxx.nt",
"liveChannels":[
{
"name":"Sony TV",
"id":1004,
"link":"https://xxx.nt",
"decryptionTicket":"https://xxxy.nt",
"viewLevel":"Too High",
"programs":
{
"totalItems":1,
"programs":[
{
"name":"Live or die",
"id":1000000000,
"catchUp":["FUN"],
"startOver":["Again"]
}
]
}
}
]
}
I have used GSON to parse the file by creating the below java classes.
Channel
LiveChannel
programs
subprograms
Channel.java
public class channel
{
String link = null;
ArrayList<liveChannels> liveChannels;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public ArrayList<liveChannels> getliveChannels() {
return liveChannels;
}
public void setliveChannels(ArrayList<liveChannels> liveChannels) {
this.liveChannels = liveChannels;
}
}
livechannel.java
public class liveChannels {
String name = null;
int id;
String link = null;
String decryptionTicket = null;
String viewLevel = null;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDecryptionTicket() {
return decryptionTicket;
}
public void setDecryptionTicket(String decryptionTicket) {
this.decryptionTicket = decryptionTicket;
}
public String getViewLevel() {
return viewLevel;
}
public void setViewLevel(String viewLevel) {
this.viewLevel = viewLevel;
}
}
After this how to parse the logic from program onwards.
"programs":
{
"totalItems":1,
program.java
public class programs {
ArrayList<sub_programs> sub_programs;
int totalItems;
public int getTotalItems() {
return totalItems;
}
public void setTotalItems(int totalItems) {
this.totalItems = totalItems;
}
public ArrayList<sub_programs> getProgramsDetails() {
return sub_programs;
}
public void setProgramsDetails(ArrayList<sub_programs> sub_programs) {
this.sub_programs = sub_programs;
}
}
sub_program.java
public class sub_programs {
String name = null;
int id;
String catchUp = null;
String startOver = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCatchUp() {
return catchUp;
}
public void setCatchUp(String catchUp) {
this.catchUp = catchUp;
}
public String getStartOver() {
return startOver;
}
public void setStartOver(String startOver) {
this.startOver = startOver;
}
}
and main look like below,
public static void main(String[] args) throws IOException
{
Gson gson = new Gson();
String contents = FileUtils.readFileToString(
new File("C:/sample.json"), "UTF-8");
channel channelHeader = gson.fromJson(contents, channel.class);
System.out.println("Channel Information --->");
System.out.println("Channel Link: " + channelHeader.getLink());
ArrayList<liveChannels> liveChannels = channelHeader.getliveChannels();
for (int i = 0; i < liveChannels.size(); i++) {
System.out.println("liveChannels Detail --->");
liveChannels liveChannelsDetail = liveChannels.get(i);
System.out.println("Channel Name : " + liveChannelsDetail.getName());
System.out.println("Channel ID : " + liveChannelsDetail.getId());
System.out.println("Channel Description Ticket: " + liveChannelsDetail.getDecryptionTicket());
System.out.println("Channel View Level : " + liveChannelsDetail.getViewLevel());
}
}
}
Could anyone please help to get the logic to parse the program from livechannel class onwards.
As programs is not an array list , What else would be an other way around to get the values.
You are missing the programs object in your liveChannels class.
public class liveChannels {
String name = null;
int id;
String link = null;
String decryptionTicket = null;
String viewLevel = null;
programs programs;
public void setPrograms (programs programs) {
this.programs = programs;
}
public programs getPrograms() {
return programs;
}
...
}
And then in your programs class, you will need to rename the sub_programs field to programs
public class programs {
ArrayList<sub_programs> programs;
...
}
As an aside, your class naming does not follow Java standards and is considered bad practice. Your classes should be named as such:
Channel
LiveChannel
Program
SubProgram
Note that this will not affect GSON's ability to parse your documents as GSON cares more about the property name than it does the actual class name of the field.
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());
}