Reputation: 19
This is the code that I have tried:
ArrayList<ArrayList<String>> select = new ArrayList<ArrayList<String>>();
ArrayList<String> selectin = new ArrayList<String>();
ResultSet lihat = st.executeQuery("select * from usersss");
while (lihat.next()){
selectin.set(0, lihat.getString("user"));
selectin.set(1, lihat.getString("password"));
selectin.set(2, lihat.getString("email"));
select.add(selectin);
}
for (int i = 0; i<select.size();i++) {
System.out.println(select.get(i));
}
This is the result:
[kursi, meja, [email protected]]
[kursi, meja, [email protected]]
[kursi, meja, [email protected]]
[kursi, meja, [email protected]]
This is the desired result (the actual table):
[paosp,skajs,[email protected]]
[fisd,mole,[email protected]]
[trem,olo,[email protected]]
[kursi,meja,[email protected]]
It seems like the selectin
list updates itself inside the select
list. Is there a way to make it not do this?
Upvotes: 1
Views: 64
Reputation: 8106
You are actually replacing the values in same reference of selectin
variable. And select
variable only contains the single reference selectin
multiple times.
Create a new ArrayList for every new element in select
, like this:
ArrayList<ArrayList<String>> select = new ArrayList<ArrayList<String>>();
ResultSet lihat = st.executeQuery("select * from usersss");
while (lihat.next()){
ArrayList<String> selectin = new ArrayList<String>();
selectin.add(lihat.getString("user"));
selectin.add(lihat.getString("password"));
selectin.add(lihat.getString("email"));
select.add(selectin);
}
for (int i = 0; i<select.size();i++) {
System.out.println(select.get(i));
}
This will create a new object of ArrayList and everytime while loop runs.
And you'll get your expected result.
Upvotes: 1
Reputation: 901
The set()
method of java.util.ArrayList
class is used to replace the element at the specified position in this list with the specified element.
boolean add(Object o)
: This method is used to append a specificd element to the end of a list.
you should replace the set()
with add()
in the loop.
while (lihat.next() ) {
selectin = new ArrayList<>();
selectin.add( lihat.getString("user") );
selectin.add( lihat.getString("password") );
selectin.add( lihat.getString("email") );
select.add( selectin );
}
Upvotes: 1
Reputation: 1731
I think your while loop should be
while (lihat.next() ) {
selectin = new ArrayList<>();
selectin.add( lihat.getString("user") );
selectin.add( lihat.getString("password") );
selectin.add( lihat.getString("email") );
select.add( selectin );
}
Since it is pass by reference, second iteration updates the firstly added arraylist. That is why the output is same after all iterations.
Upvotes: 2