How to make it possible to check the id for a match, and give an error only id

public static final String FILE_PATH = "developers.txt"; public void create(Developer developer) { Writer writer = null; String str = developer.getId() + "," + developer.getFirstName() + "," + developer.getLastName() + "," + developer.getSpecialty() + "," + developer.getSalary(); try { writer = new FileWriter(FILE_PATH, true); writer.write(str + '\n'); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } 
  • On coincidence with what? - test123
  • To check if the data is already in the file - you need to read the file, for example in Set, then everything becomes obvious - the set cannot contain two identical values, and the set has the contains method, which determines whether there is an element in the collection. Also, I note that you do not close the file, although this is not related to the subject matter. - test123

1 answer 1

First make a lot of Developer using HashSet<Developer> . This set will remove duplicates itself if you override the hashCode method from the Developer class. For example, you can override the hashCode method as follows:

 @Override public int hashCode() { return id; } 

Then create a set:

 HashSet<Developer> tests = new HashSet<>(); 

And add to it all the objects of the Developer class that you want to write to the file. After adding all the objects of the Developer class will be added to the set, except for duplicates.

However, be careful, after overriding the hashCode method, you may change other parts of the code in which you use this class.

The best solution would be to create additional methods that collect a list of all non-duplicate objects.

 private List<Developer> getDeveloperList(List<Developer> totalDeveloperList){ if(totalDeveloperList == null || totalDeveloperList.isEmpty()){ return totalDeveloperList; } List<Developer> developerList = new ArrayList<>(); for(Developer developer : totalDeveloperList){ if(!hasDeveloper(developerList, developer)){ developerList.add(developer); } } return developerList; } private boolean hasDeveloper(List<Developer> developerList, Developer checkableDeveloper){ if(developerList == null || developerList.isEmpty()){ return false; } for(Developer developer : developerList){ if(developer.getId() == checkableDeveloper.getId()){ return true; } } return false; }