I am using the following code and at the end i saw in calssEntries list the last values duplicated
i mean if i debug it i can see the right data but in the second iteration the values of the first data entries
are override and i see the second twice and so on
what i miss here?
String memberName = null;
String memberValue = null;
List<String> memberList = new ArrayList<String>();
List<String> memberValueList = new ArrayList<String>();+ArrayList<ClassEntry> calssEntries = new ArrayList<ClassEntry>();
...
while (dataRow != null) {
memberList.clear();
memberValueList.clear();
for (int i = 1; i < dataArray.length; i += 2) {
memberName = dataArray[i];
memberList.add(memberName);
memberValue = dataArray[i + 1];
memberValueList.add(memberValue);
}
ClassEntry classEntry = new ClassEntry();
classEntry.setClassName(className);
classEntry.setMemberName(memberList);
classEntry.setMemberValue(memberValueList);
calssEntries.add(classEntry);
....
I think the problem is that you need to create a new instance of memberList and memberValueList in the while loop. Something like:
calssEntries = new ArrayList<ClassEntry>();
...
while (dataRow != null) {
List<String> memberList = new ArrayList<String>();
List<String> memberValueList = new ArrayList<String>();
...
...
In your code, entries of calssEntries are referring to the same(single) instance of memberList and memberValue.
try this
for (int i = 1; i < dataArray.length; i += 2) {
int j = i;
memberName = dataArray[i];
memberList.add(memberName);
memberValue = dataArray[j + 1];
memberValueList.add(memberValue);
}
Related
When I try to insert a value relating to its key the value is not inserting inside the map. It seems like the "ids" doesn't have any value in it but it does.
Map<String, Vector<String>> graph = new HashMap<String, Vector<String>>();
ArrayList<String[]> words = new ArrayList<String[]>();
Vector<String> ids = new Vector<String>();
String[] id = null;
Scanner scanner = new Scanner(new FileReader(fInName));
while (scanner.hasNextLine()) {
words.add(scanner.nextLine().split("\\s+"));
}
for(int i = 0; i < words.size(); i++) {
id = words.get(i)[1].split("[,]", 0);
for(int j = 0; j < id.length; j++) {
ids.add(j, id[j]);
}
graph.put(words.get(i)[0], ids);
id = null;
ids.clear();
}
for (Map.Entry<String, Vector<String>> entry : graph.entrySet()) {
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
The put() function works by reference. So
put (key, ids)
stores a reference (memory pointer) to the same ids object that you are running the clear() function on. Trying to 'clean up' your memory is laudable, but in this case you're shooting your own foot. What you want is something like this
Map<String, Vector<String>> graph = new HashMap<String, Vector<String>>();
ArrayList<String[]> words = new ArrayList<String[]>();
Vector<String> ids;
String[] id = null;
Scanner scanner = new Scanner(new FileReader(fInName));
while (scanner.hasNextLine()) {
words.add(scanner.nextLine().split("\\s+"));
}
for(int i = 0; i < words.size(); i++) {
id = words.get(i)[1].split("[,]", 0);
ids = new Vector<String>();
for(int j = 0; j < id.length; j++) {
ids.add(j, id[j]);
}
graph.put(words.get(i)[0], ids);
}
I have a native hibernate query that returns a list of objects to me, with a for loop I would like to populate a class list, but I do not laugh because the list is always populated by the last element. Where's the error?
This the code:
...
List<Object[]> results = query.list();
List<PackDisTask> packageDistTasks = new ArrayList<PackDisTask>();
PackageDistributionTaskId taskId = new PackageDistributionTaskId();
Object[] result = null;
String r = "";
for (int i = 0; i < results.size(); i++) {
PackageDistributionTask pdt = new PackageDistributionTask();
result = results.get(i);
if (result[0] != null) {
r = result[0].toString();
taskId.setFkPackageDistribution(Integer.parseInt(r));
}
if (result[10] != null) {
r = result[10].toString();
taskId.setFkTaskType(Integer.parseInt(r));
}
pdt.setId(taskId);
packageDistTasks.add(pdt);
}
I'm having some trouble accessing my 2D array (myArray) outside of this the loop. I want to access it using other methods, but I can't even access it in this method. It prints out correctly as it's looping, but the test print of
System.out.println(myArray[10][2]);
is always null. So it's like the array isn't actually filling or something. Anyone know what I'm doing wrong here?
package titanic;
import java.io.*;
import java.util.*;
public class Titanic {
public static final int ROW = 1309;
public static final int COLUMN = 6;
public static String [][] myArray = new String[ROW][COLUMN];
public static String[][] arraySetup(){
int recordCounter = 0;
String[][] myArray = new String[ROW][COLUMN];
String[] name = new String [ROW];
try {
BufferedReader br = new BufferedReader(new FileReader("C:/Users/Tom/Desktop/Titanic.txt"));
String line;
for (int i = 0; i < 1309; i++){
while((line = br.readLine()) != null){
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(myArray[10][2]);
System.out.println(recordCounter + " records.");
return myArray;
}
As you have you while loop inside for loop that is used to for indexing your output array while loop always writes into the myArray[0][0] to myArray[0][5]
for (int i = 0; i < 1309; i++){ // i is 0
while((line = br.readLine()) != null){ // you go through all the lines while i is 0
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
Because of that your check always returns null.
System.out.println(myArray[10][2]);
I think the problem in your code is right there
for (int i = 0; i < 1309; i++){ // you loop 1308 time
while((line = br.readLine()) != null){ /* in each loop, you loop
until you have read all the file so you read 1308 time the file. But when
you reach the end of file on the first iterration, it wont read the file on the 1307
other iterration and all data will be store in myArray[0][0-5]*/
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
myArray[i][2] = tmp[2];
myArray[i][3] = tmp[3];
myArray[i][4] = tmp[4];
myArray[i][5] = tmp[5];
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
}
Don't use for and while loop together. During the first for loop, your while reads all file contents and all other array positions remain empty.
Try this instead:
int i=0;
while ((line = br.readLine()) != null){
String tmp[] = line.split("\t");
myArray[i][0] = tmp[0];
myArray[i][1] = tmp[1];
...
myArray[i][5] = tmp[5];
i++;
System.out.println("myArray[i][5] = " + myArray[i][5]);
recordCounter++;
}
I have an array with 2 positions, each one contains a list of "ids_alunos", the first position has ids_alunos: "1,2,3" and the second:"4,5" but what is happening when I add the ids in my array is this, the first position gets "1,2,3" values and the second: "1,2,3,4,5". why is this happening?
public ArrayList<CadastraEscolas> getFilhos(String mToken) throws Exception {
String[] resposta = new WebService().get("filhos", mToken);
if (resposta[0].equals("200")) {
JSONObject mJSONObject = new JSONObject(resposta[1]);
JSONArray dados = mJSONObject.getJSONArray("data");
mArrayList = new ArrayList<CadastraEscolas>();
mGPSList = new ArrayList<GPSEscolas>();
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i).getJSONObject("escolas");
JSONArray escolas = item.getJSONArray("data");
for (int j = 0; j < escolas.length(); j++) {
JSONObject jItens = escolas.getJSONObject(j);
mCadastraEscolas = new CadastraEscolas();
mGPSEscolas = new GPSEscolas();
mCadastraEscolas.setId_escola(jItens.optInt("id_escola"));
mGPSEscolas.setId_escola(jItens.optInt("id_escola"));
JSONObject alunos = jItens.optJSONObject("alunos");
JSONArray data = alunos.getJSONArray("data");
if (data != null) {
ArrayList<Filhos> arrayalunos = new ArrayList<Filhos>();
for (int a = 0; a < data.length(); a++) {
mFilhos = new Filhos();
JSONObject clientes = data.getJSONObject(a);
mFilhos.setId_aluno(clientes.optInt("id_aluno"));
arrayalunos.add(mFilhos);
idsAlunos += ";" + arrayalunos.get(a).getId_aluno().toString();
mGPSEscolas.setIds_alunos(idsAlunos);
}
mCadastraEscolas.setalunos(arrayalunos);
}
mArrayList.add(mCadastraEscolas);
mGPSList.add(mGPSEscolas);
}
}
return mArrayList;
} else {
throw new Exception("[" + resposta[0] + "] ERRO: " + resposta[1]);
}
}
You probably want to initialize idsAlunos at the same time as mGPSEscolas, so where you do:
mGPSEscolas = new GPSEscolas();
you could also do:
idsAlunos = "";
otherwise idsAlunos gets appended to with every new mGPSEscolas.
I am using opencsv to parse two csv files. I only copy some values from the two files.
I have a seperate function which processes the CDax.csv. Which looks like that:
public HashMap<String,String> readCDax() throws Exception {
String csvDaxFile = "C:\\Users\\CDAX.csv";
CSVReader reader = new CSVReader(new FileReader(csvDaxFile), ';');
String [] line;
HashMap<String, String> cdaxMap = new HashMap<String, String>();
while ((line = reader.readNext()) != null) {
cdaxMap.put(line[0], line[7]);
}
System.out.println("Process CDax File!");
reader.close();
return cdaxMap;
}
My main method is run() which I execute in my main method:
public void run() throws Exception {
while ((firstLine = reader.readNext()) != null && (secondLine = reader.readNext()) != null && i<10) {
//fileName of the String
fileName = firstLine[0];
writerPath = "C:\\Users\\" + fileName + ".csv";
//write csv file
CSVWriter writer = new CSVWriter(new FileWriter(writerPath), ';');
//write Header
//String[] entries = "Name;Date;TotalReturn;Currency".split(";");
String [] entries = {"Name","Date", "TotalReturn", "Currency"};
writer.writeNext(entries);
//create Content
//companyName of the String
companyName = secondLine[1];
//currency
currency = secondLine[2];
//dates
dateList = new ArrayList<String>();
for(int p = 3; p < firstLine.length; p++) {
dateList.add(firstLine[p]);
}
//total returns
returnList = new ArrayList<String>();
for(int j = 3; j < secondLine.length; j++) {
returnList.add(secondLine[j]);
}
// cDaxList
cDaxList = new ArrayList<String>();
for(int j = 1; j <dateList.size(); j++) {
if(cDaxMethodValuesMap.containsKey(dateList.get(j))){
cDaxList.add(cDaxMethodValuesMap.get(dateList.get(j)));
} else{
dateList.add("na"); // I get the error here!
}
}
if(dateList.size()!=returnList.size()) {
System.out.println("Dates and Returns do not have the same length!");
}
int minSize = Math.min(dateList.size(), returnList.size());
//"Name;Date;TotalReturn;Currency"
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m < minSize; m++) {
data.add(new String[] {companyName, dateList.get(m), returnList.get(m), currency, cDaxList.get(m)});
}
writer.writeAll(data);
//close Writer
writer.close();
i++;
System.out.println(fileName + " parsed successfully!");
}
System.out.println("Done");
}
However when I run my program I get:
Process CDax File!
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2760)
at java.util.Arrays.copyOf(Arrays.java:2734)
at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
at java.util.ArrayList.add(ArrayList.java:351)
at com.TransformCSV.main.ParseCSV.run(ParseCSV.java:109)
at com.TransformCSV.main.ParseCSV.main(ParseCSV.java:21)
I am getting the error in this method:
cDaxList = new ArrayList<String>();
for(int j = 1; j <dateList.size(); j++) {
if(cDaxMethodValuesMap.containsKey(dateList.get(j))){
cDaxList.add(cDaxMethodValuesMap.get(dateList.get(j)));
} else{
dateList.add("na"); //I get the error here!!!
}
}
I tried to put up the heapsize via the vm settings, however I do not think that this should be done because I only read in both csv files only 3000 values.
I appreciate your reply!
Your loop:
for(int j = 1; j <dateList.size(); j++) {
is looping through dateList but in that loop you are adding to dateList:
dateList.add("na"); //I get the error here!!!
so dateList will get bigger and bigger until you run out of memory. dateList.size() is evaluated every time through the loop, not once at the beginning.