Detect and Remove duplicates in ArrayList? - java

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.

Related

Why wouldn't Java Map work? The function .put() not inserting the value and only inserting the key

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);
}

How to display Object array in JTable?

This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}

JSON to Hold Course, Student, and Assignment Data

I am trying to use JSON to contain data related to a class/course. The idea is that there are 40 classes/courses and that each class/course contains 50 students, and each student has 100 assignments. Below is what I've figured out so far. How can I modify it to hold all the gradebook data, as listed above?
public void x(){
JSONObject courseJSONObject = new JSONObject();
JSONArray courseJSONArray = new JSONArray();
JSONObject studentJSONObject = new JSONObject();
JSONArray studentJSONArray = new JSONArray();
JSONObject assignmentJSONObject = new JSONObject();
JSONArray assignmentJSONArray = new JSONArray();
for(int i = 0; i < 40; i++){
courseJSONObject.put("course name", course.getName());
courseJSONObject.put("course teacher", course.getTeacher());
courseJSONArray.put(courseJSONObject);
courseJSONObject = new JSONObject();
for(int j = 0; j < 50; j++){
studentJSONObject.put("student name", course.student.getName());
studentJSONObject.put("student id", course.student.getid());
studentJSONObject.put("student final grade",
course.student.getfinalgrade());
studentJSONArray.put(studentJSONObject);
studentJSONObject = new JSONObject();
for(int k = 0; k < 100; k++){
assignmentJSONObject.put("assignment name", getAssignmentName());
assignmentJSONObject.put("category", getAssignmentCategory());
assignmentJSONObject.put("date", getAssignmentDate());
assignmentJSONObject.put("grade",
course.student.getAssignmentGrade());
assignmentJSONArray.put(assignmentJSONArray);
assignmentJSONObject = new JSONObject();
}
}
}
JSONArray courses = new JSONArray();
for(int c = 0; i < 40; c++) {
JSONObject course = new JSONObject();
// Add course details
JSONArray students = new JSONArray();
for(int s = 0; s < 50; s++) {
JSONObject student = new JSONObject();
// Add Student details
JSONArray assignments = new JSONArray();
for(int a = 0; a < 100; a++) {
JSONObject assignment = new JSONObject();
// Add assignment details
assignments.put( assignment );
}
student.put( "assignments", assignments );
students.put( student )
}
course.put( "students", students );
courses.put( course );
}

Why am I getting duplicates when combining multiple ArrayLists?

Why I am getting duplicate entries in my ArrayList<String[]>?
allStepsJSONStringArray contains an array of single strings in the format of JSON
I loop through and pass each JSON string to a function that writes it to a temporary internal file
I read the file
Then pass it to getStepsArray() which breaks down the JSON string and puts each entry into a String[]
Loop to add to master ArrayList - allStepsArray
for (int i = 0; i < allStepsJSONStringArray.size(); i++) {
writer.writeToInternal(allStepsJSONStringArray.get(i));
reader.readFromInternal(writer.filename);
stepsArray = reader.getStepsArray();
for (int s = 0; s < stepsArray.size(); s++) {
allStepsArray.add(stepsArray.get(s));
}
}
getStepsArray()
public ArrayList<String[]> getStepsArray() {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("steps");
String stepOrder = null;
String stepName = null;
String stepType = null;
String stepId = null;
String checklistId = null;
String checklistName = null;
for (int i = 0; i < jArray.length(); i++) {
stepOrder = jArray.getJSONObject(i).getString("order");
stepName = jArray.getJSONObject(i).getString("name");
stepType = jArray.getJSONObject(i).getString("type");
stepId = jArray.getJSONObject(i).getString("id");
checklistId = jObject.getString("checklistId");
checklistName = jObject.getString("checklistName");
stepsArray.add(new String[] {stepOrder, stepName, stepType, stepId, checklistName, checklistId});
}
} catch (Exception e) {
e.printStackTrace();
}
return stepsArray;
}
Word for word:
Because you don't seem to ever reset stepsArray. The second time you add elements to it, the previous elements will still be there and will get added to allStepsArray again.

How to convert java arraylist to json array store data using java and jsp and extjs

is there any way to convert array list to json store input data using jsp and java for extjs.
means i need to get data for json store from jsp page and java arraylis
Here you go hope this helps you... Here im getting state values from db..
String response = "id,State#";
List stateList = new ArrayList<>();
//DB call
for (int i = 0; i < stateList.size(); i++) {
response += stateList.get(i).gets_code() + ",";
response += stateList.get(i).getS_name() + "#";
}
StringTokenizer st = new StringTokenizer(response , "|");
String finalMsg = null;
String str1 = null;
while (st.hasMoreElements()) {
String token = st.nextToken();
finalMsg = token;
}
JSONObject object = new JSONObject();
stbuffer.append("{\"root\":[");
String[] data = finalMsg.split("#");
int len = data.length;
String[] headings = data[0].split(",");
for (int x = 1; x < len; x++) {
String[] data1 = data[x].split(",");
int len1 = data1.length;
for (int y = 0; y < len1; y++) {
object.put(headings[y], data1[y]);
}
stbuffer.append(object);
stbuffer.append(",");
}
stbuffer.append("]}");
String result = stbuffer.toString();
result = result.replace(",]", "]");

Categories