3
I’m having trouble adding a different object to a list of objects whenever I use her add, I know what the problem is but I don’t know how to fix it, follow the code List class
public class Lista {
NodeLista inicio;
NodeLista fim;
public Lista (){
inicio = null;
fim = null;
}
public boolean isEmpty(){
return inicio == null;
}
public int size(){
if(isEmpty()){
return 0;
}
NodeLista aux = inicio;
int cont = 1;
while(aux.proximo != inicio){
cont++;
aux = aux.proximo;
if(aux == inicio){
break;
}
}
return cont;
}
public void add(NodeTree arvore){
NodeLista novo = new NodeLista(arvore);
if(isEmpty()){
inicio = novo;
fim = novo;
inicio.proximo = null;
fim.proximo = null;
}else {
fim.proximo = novo;
fim = novo;
fim.proximo = null;
}
}
public boolean validarElemento(String elemento){
NodeLista aux = inicio;
for (int i = 0; i < size(); i++) {
if(aux.arvore.elemento.equals(elemento)){
return true;
}
aux = aux.proximo;
}
return false;
}
}
Nodetree class
public class NodeTree {
String elemento;
Lista filhos;
public NodeTree(String elemento){
this.elemento = elemento;
filhos = new Lista();
}
}
Nodelist class
public class NodeLista {
NodeTree arvore;
NodeLista proximo;
NodeLista anterior;
public NodeLista(NodeTree arvore){
proximo = null;
anterior = null;
this.arvore = arvore;
}
}
Main
public class MainTree {
public static void main(String[] args) {
Lista lista = new Lista();
System.out.println(lista.size());
NodeTree arvore = new NodeTree("1");
lista.add(arvore);
NodeTree arvore2 = new NodeTree("2");
lista.add(arvore2);
arvore2.elemento = "3";
System.out.println(lista.inicio.arvore.elemento);
System.out.println(lista.inicio.proximo.arvore.elemento);
System.out.println(lista.size());
}
}
Console
0 1 3 2
Desired exit
0 1 2 2
Every time I add a nodetree obj to the list and change its element by the object itself, I am changing in the list tbm, there is some way not to change in the list?
Please avoid long discussions in the comments; your talk was moved to the chat
– Maniero