I know this is a very basic question, but I have searched and have not found a suitable answer for my problem. I have an ArrayList of Objects which is populated from a Scanner. When I try to print out all the elements in the list, I only get the last element repeated as many times as objects in the list.
First the Object class:
public class Colors {
String name;
@Override
public String toString(){
return name.toString();
}
}
Now the main class:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Vec {
public static void main(String[] args) {
Colors col= new Colors();
List <Colors> l = new ArrayList<>();
boolean flag = true;
while(flag == true){
System.out.println("Type in name of color");
Scanner kb = new Scanner (System.in);
col.name = kb.next();
l.add(col);
for (int j= 0; j<l.size();j++) {
Object g = (Object)l.get(j);
System.out.println("Name of color: "+g);
}
}
}
}
What exactly am I doing wrong?
You are declaring objects in Java by using the new
keyword. You are only declaring one instance of Colors
, then changing its name over and over again. Then adding that same Colors
to the list over and over. What you need to do is to change where you are declaring your Colors
, that can be done inside the while
statement.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Vec
{
public static void main(String[] args) {
List <Colors> l = new ArrayList<>();
boolean flag = true;
Scanner kb = new Scanner (System.in);
while (flag) {
System.out.println("Type in name of color");
Colors col = new Colors ();
col.name = kb.next();
l.add(col);
for (int j = 0; j<l.size();j++) {
Object g = (Object)l.get(j);
System.out.println("Name of color: "+g);
}
}
}
}
The difference here is that col
is now re-declared in the local scope of of your while
statement.
Small notes, these are off-topic and aimed at codereview rather than answering the question.
while (flag == true)
, no need to compare against true
. You also do not need to creaste a new Scanner
all the time.
I suggest to use better names for your variables. l
, col
, kb
, flag
could basically be anything.
Some recommendations (they are just that, recommendations):
Colors
, now Colors
is misleading as well, as it is only one color, I recommend to change the class name to Color
and the list l
to colors
. scanner
instead. running
, playing
, on
. Another addition is that since you know what your l
stores you can use a for
each instead.
for (Colors c : l) {
System.out.println("Name of color: " + c);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.