Reputation: 35
I am trying to read a file and pass it to a class called "Allabaque" that has a String and two List. When I have finished reading the first abaque I want to clear the two Lists so I can get the nexts values but if I clear the List, even if I do it after adding the new abaque, the function passes me the new abaque with the two empty Lists. Here is the code:
public void importFrom(String filename) {
try (
FileInputStream fis = new FileInputStream(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));) {
String line;
String line2;
int c = 0;
List<String> Pression = new ArrayList<>();
List<String> Couple = new ArrayList<>();
List<String> P2 = new ArrayList<>();
List<String> C2 = new ArrayList<>();
String Cle = "null";
while ((line = reader.readLine()) != null) {
if (c == 2 && !"|".equals(line)) {
String[] arg = line.split("-");
boolean u = Pression.add(arg[0]);
boolean u2 = Couple.add(arg[1]);
}
if (c == 1) {
Cle = line;
c = 2;
//System.out.printf("%s",Cle);
}
if ("|".equals(line)) {
c = 1;
if (!"null".equals(Cle)) {
//P2 = Pression;
//C2 = Couple;
addAbaque(new Abaque(Cle, Pression, Couple));//addAbaque(new Abaque(Cle,P2,C2));
Couple.clear();
Pression.clear();
}
}
}
} catch (IOException ioe) {
System.out.printf("Erreur import");
}
}
The addAbaque method is the simple
public void addAbaque(Abaque abaque) {
mAbaques.add(abaque);``
}
Using the debug I think I have found that it's a problem with the memory but I reaaly dont know how to fix it.
I've tried also with two intermedieries List, I putted it like comments, but still nothing.
Upvotes: 1
Views: 68
Reputation: 393801
Clearing the Couple
and Pression
lists also clears the lists previously passed to the Abaque
constructor, since you are passing List
references to the constructor, not copies of the lists.
You can either pass new Lists to the constructor :
addAbaque(new Abaque(Cle,new ArrayList<String>(Pression),new ArrayList<String>(Couple)));
Or create new Lists instead of clearing the old ones, i.e. replace
Couple.clear();
Pression.clear();
with
Couple = new ArrayList<>();
Pression = new ArrayList<>();
The latter alternative is probably more efficient, since you don't have to copy the contents of the original Lists to new Lists, and you don't have to clear any Lists.
Upvotes: 1