Object Array add only adds last record - java

I am trying to add an object to an arraylist.
The object is defined as:
ExercisesGroup group = new ExercisesGroup();
Array List defined as:
ArrayList<ExercisesGroup> groups = new ArrayList<ExercisesGroup>();
I am then populating the object in a loop (rs is a result set from a database):
while (rs.next()){
group.setExerciseGroupId(rs.getInt("idbodyarea"));
group.setExerciseGroupDescription(rs.getString("bodyareadescription"));
groups.add(group);
}
When I return the arraylist 'groups' the correct number of results are added, however the data is all the same, i.e. the last record is added for every slot.
<exerciseGroupsReturn>
<exerciseGroupDescription>Description2</exerciseGroupDescription>
<exerciseGroupId>2</exerciseGroupId>
</exerciseGroupsReturn>
<exerciseGroupsReturn>
<exerciseGroupDescription>Description2</exerciseGroupDescription>
<exerciseGroupId>2</exerciseGroupId>
</exerciseGroupsReturn>
Any idea what I am doing wrong?

You need to create a new instance of the object on every iteration:
while (rs.next()){
group = new ExercisesGroup();
//...
}
Also, it would be better if you change the declaration of groups variable from ArrayList<ExercisesGroup> to List<ExercisesGroup>. Refer to What does it mean to "program to an interface"?

It looks like you're creating your ExcerciseGroup outside of the loop so you're always referencing the same object. Put the ExerciseGroup constructor inside the loop.

Related

method add in ArrayList<ClassName> is not applicable for the arguments (String)

I'm trying to read a .txt file that contains several lines with the name of a professional carreer in each one of them. I've created a Scanner but whenever I want to add what the scanner have just read and try to add it to the arrayList, this error pops up
The method add(ClassName) in the type ArrayList is not applicable for the arguments (String)
ArrayList<Claseqla> clista = new ArrayList<Claseqla>();
Scanner s = new Scanner(new File("texto.txt"));
while(s.hasNextLine())
{
**clista.add(s.nextLine());**
}
This is the piece of code inside another class;
The bold marked line is where the error pops up.
clista only has 2 attributes but I'd like to add them to the list with just one String element filled and the other empty (Is that even possible?)
s.nextLine() returns a String. But your ArrayList has generic type Claseqla. You need to create a Claseqla object using the string you grab from the s.nextLine() call, and then add that object to your ArrayList.
I guess you are trying to say that the class Claseqla has 2 attributes. If so, then you can create a Claseqla object and set the value of one of the attributes with s.nextline()
while(s.hasNextLine())
{
Claseqla cq = new Claseqla();
cq.setCareer(s.nextLine());
clista.add(cq);
}
This is asumming that you have an attribute named career (String) in your Claseqla class with its respective setter function.

How do I use field.get(obj) on a List field?

I want to get a private List field from a class, but I don't know what argument to give to field.get to successfully get the List from the class. My current code produces a java.lang.IllegalArgumentException.
Field field = Minecraft.class.getDeclaredField("defaultResourcePacks");
field.setAccessible(true);
List<IResourcePack> changedList = new ArrayList<IResourcePack>();
List<IResourcePack> list = (List<IResourcePack>) field.get(changedList);
In your example:
List<IResourcePack> changedList = new ArrayList<IResourcePack>();
List<IResourcePack> list = (List<IResourcePack>) field.get(changedList);
You are using get() the wrong way. The expected argument must be an Object of class Minecraft; and get pulls the content of the field that you identified earlier on. In other words: you do not need an input parameter "changedList"; you need one that is a Minecraft object.
I think you should use get(objOfMinecraft)

Converting JDBC Result Set to Nested Array List

Using JDBC, I have managed to run a query on a database and receive a result set (rs). Using this information, I hope to generate a nested array list.
// Created Array List
public static ArrayList<ArrayList<SessionRecord>> tempSessionOrg = new ArrayList<ArrayList<SessionRecord>>();
The inner list needs to be grouped by the information returned from the first column. And this is all I've got thus far:
while(rs.next()) {
SessionRecord temp = new SessionRecord(rs.getString("SessionID"),rs.getString("NetworkAddress"),rs.getString("EventType"),rs.getString("Time"),rs.getString("Name"),rs.getString("SessionType"),rs.getString("ProcessType"));
}
I've already written a very similar program, with the exception that it places the result set into a single ArrayList without nesting. Unfortunatley, this analagous piece of code hasn't really helped me come up with a solution.
while(rs.next()) {
dbSession.add(new SessionRecord(rs.getString("name"),rs.getString("ParticipantName"),rs.getString("GuestLoggedOnUsername"),rs.getString("GuestMachineName"),rs.getString("inicio"),rs.getString("diferencia")));
}
Any suggestions?
EDIT:
At this point, I have the following two blocks one code.
One:
public static ArrayList<SessionRecord> singleSessionRecords = new ArrayList<SessionRecord>();
public static ArrayList<ArrayList<SessionRecord>> tempSessionOrg = new ArrayList<ArrayList<SessionRecord>>();
Two:
while(rs.next()) {
singleSessionRecords.add(new SessionRecord(rs.getString("SessionID"),rs.getString("NetworkAddress"),rs.getString("EventType"),rs.getString("Time"),rs.getString("Name"),rs.getString("SessionType"),rs.getString("ProcessType")));
}
Map<String, List<SessionRecord>> byID = singleSessionRecords.stream().collect(Collectors.groupingBy(SessionRecord::SessionID));
tempSessionOrg.add((ArrayList<SessionRecord>) Map.values());
I'm receiving a type mismatch error for the Map line and that I can't make a static reference to a non-static method in the final line. The later of the two is easy enough of a fix for me, but I'm not sure how to implement the Map properly.
Are you using Java 8?
If so this could easily be achieved by this code :
Map<String, List<SessionRecord>> byName
= temp.stream()
.collect(Collectors.groupingBy(SessionRecord::name));
In this example I'm grouping the sessionRecords by name, you can easily change this to fit your grouping needs.

Can we dynamically create an object by checking existance?

For the following class I want to access an object if the name equals to something, let's say "you". Otherwise I want to create it.
I want to check if an object exists that has the name as 'you' and then add entries to the ArrayList contInstances. If such an instance doesn't already exist I want to create it. Next time I might have to use the same object so that I can add some more entries to the ArrayList.
public class Values {
String name;
ArrayList<anotherClass> classInstances = new ArrayList<anotherClass>();
}
This happens to be in a loop. How can I do that?
Edit: I'll quote an example here:
if (an object exists that contains field 'name' == 'YOU'){
add entries to the array list directly using the available object
}
else {
create a new object and set the 'name' = 'YOU';
add entries to the array list;
}
It sounds kind of like you want to have a cache by name. Instead of an ArrayList, consider using a Map<String, AnotherClass> to keep track of Name->Object mappings.
You can then use this approach:
Map<String, AnotherClass> instances = new LinkedHashMap<String, AnotherClass>();
for (...) {
String name = getNextName();
AnotherClass instance = instances.get(name);
if (instance == null) {
instance = makeInstance(name);
instances.put(name, instance);
}
useInstance(name, instance);
}
After that loop is finished, if you still want a List<AnotherClass>, you can use return new ArrayList<AnotherClass>(instances.values());

How to view all items in arraylist java?

In my android application I want to be able to add a string value to a static arraylist I have declared on my main android activity. The logic goes like this:
1) When you click a button and an activity starts. On the oncreate method I want to save the name of the class that is the current activity to a string value. For example:
String className = "com.lunchlist.demo";
After this value is assigned I want to immediately add this string value to a Static ArrayList I have declared in my main android activity (meaning first android activity that starts) After adding the value
I did something like this:
static String List<String> members = new ArrayList<String>();
This is declared in my main activity. Now when I click a button to start another activity I use this to add the string classname for that current activity to my arraylist in my oncreate method:
String className = "com.lunchlist.demo"
members.add(className);
My question is now, would this add the string value to my arraylist and save it for later use? For example If I click three different buttons this will add three different className values to the arraylist. Would this then store a string value that would hold three different string values for my members arraylist? How would I check each item in my arraylist to see if the values are being added when a new activity is started?
I'm asking this because I will need to retrieve this and store these values using shared preferences and later retrieve them and starting an intent using the string value which is the class to start the activity. I got the activity to start with a string value of a class name I'm just having trouble storing them.
Answering to all of your questions:
would this add the string value to my arraylist and save it for later
use?
Yes. Your code seems perfect to do it with no problems.
For example If I click three different buttons this will add three
different className values to the arraylist. Would this then store a
string value that would hold three different string values for my
members arraylist?
If you tell to your button's onClickListener to add a string to the members ArrayList then it will be done and no matter if you already had previously added that member to the ArrayList because array lists don't care if there is duplicated data or not.
How would I check each item in my arraylist to see if the values are
being added when a new activity is started?
You have to iterate your array list with a for or a for-each cicle and then print that member name as a log entry.
For-each cicle
for (String member : members){
Log.i("Member name: ", member);
}
Simple For cicle
int listSize = members.size();
for (int i = 0; i<listSize; i++){
Log.i("Member name: ", members.get(i));
}
If you try to print/ log a value which index is out of range, i.e., i < 0 || i >= listSize then a IndexOutOfBoundsException will be thrown and crash your app.
Iterate using For-Each introduced in Java from Java 1.5 :
for (String s : members){
Log.d("My array list content: ", s);
}
See this link for further details:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
Try this:)
We can implement by these two way
foreach
for loop
String type arraylist
ArrayList<String> limits = new ArrayList<String>(); // String arrayList
Using foreach
for (String str_Agil : limits) // using foreach
{
Log.e("Agil_Limits - " , str_Agil);
}
Using forloop
for(int agil=0; agil<=limits.size(); agil++) // using for loop
{
Log.e("Agil_Limits - " , limits.get(agil).toString());
}

Categories

Resources