Reputation: 14219
I have a text file and in it there is a list of city:
I would load every line on a list in java without duplicate.I tried to load it but when I print the list I have duplicate.
private Set<Comune> comunilist;
public ReteStradale(){
comunilist=new HashSet<Comune>();
}
private void loadComuni(String sname){
try{
BufferedReader reader=new BufferedReader(new FileReader(sname));
String id_street=reader.readLine();
while(id_street!=null){
int length=Integer.parseInt(reader.readLine());
String comune_par=reader.readLine();
String comune_arr=reader.readLine();
Comune com=new Comune(comune_par);
comunilist.add(com);
id_street=reader.readLine();
}
}
catch(FileNotFoundException ffe){
System.err.println("Error: the file does not exist!");
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
here is my code.please don't considerer the name of element but the code
Upvotes: 0
Views: 592
Reputation: 7317
I think the problem is with the "Comune" class. You didn't show us the code for that and I assume you did not implement hashCode() and equals() in it.
The default implementation of them, which is from Object, is based on the memory address of the object as opposed to its contents. Thus even if you create two Comune object with the same city name, they will be treated as totally different objects by the Set.
In this case, you should either store the names as Strings directly or override the two methods for your class.
Upvotes: 0
Reputation: 4324
I would recommend using a delimiter for the cities in your cities.
New York, Los Angeles, etc...
Then read the cities into a String array or ArrayList or something similar.
Once you have that, you can put the collection into a Set implementation which does not allow duplicates.
Set<String> mySet = new HashSet<String>(myArrayList);
Regards!
Upvotes: 0
Reputation: 601
When you get each new city, place the String into a Set. This will prevent duplicates. Then you can print the entries from the Set.
So long as the Strings you are getting from the text file are truly the same then you will be unable to add duplicates.
Upvotes: 0
Reputation: 2301
You can use the Set Data Type, which stores only unique values.
interface - http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
one implementation - http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
Upvotes: 3