LinkedList outputs ONLY last element
Hello guys
I'm working on Collection framework and doing random exercises off my head. I want to fill a linked list with objects and then display the elements of the linked list, it only output the last element of the list.
here is my code
Code Java:
import java.util.*;
class MyClass{
String name;
int age;
Scanner scan = new Scanner(System.in);
void setName(){
System.out.println("name:");
this.name = scan.next();
}
String getName(){
return this.name;
}
}
public class Napster {
public static void main(String[] args){
MyClass c = new MyClass();
List<MyClass> l = new LinkedList<MyClass>();
c.setName();
l.add(c);
c.setName();
l.add(c);
for(MyClass s : l){
System.out.println("Name =>"+ s.getName());
}
}
}
Re: LinkedList outputs ONLY last element
Code :
c.setName();
l.add(c);
c.setName();
l.add(c);
You update the name of an object and add it to the list. Then you update the name again of the same object and add it again to the list again.
Do you see what's wrong here?
Re: LinkedList outputs ONLY last element
Quote:
Originally Posted by
OutputStream
Code :
c.setName();
l.add(c);
c.setName();
l.add(c);
You update the name of an object and add it to the list. Then you update the name again of the same object and add it again to the list again.
Do you see what's wrong here?
thanks a lot! now I see my problem.
I edited as follow (in case this helps anybody) :
Code :
l.add(new MyClass());
l.get(0).setName();
l.add(new MyClass());
l.get(1).setName();
for(MyClass s : l){
System.out.println("Name => "+ s.getName());
}
Re: LinkedList outputs ONLY last element