Get value of an element of a list - java

I need to access the value of an element in a list in a different class. Here is how it goes:
In class DocumentManager.java:
Domain.Form form = new Domain.Form();
Services.Form wsForm = new Services.Form();
What I have not been able to do is to assign the value of versionLabel in the similar manner. I think this is because "version" is a List in "form" and String in "wsForm". I would want something like the following:
wsForm.setVersionLabel(form.getVersions().getLabel());
"label" has a String value. I want to assign that to versionLabel in "wsForm".
Thank you in advance.

You are working with a List and therefore you have to call
wsForm.setVersionLabel(form.getVersions().get(/index here/).getLabel());
What you were doing is calling a non-existing method for Lists on a List. In this way you can get to a certain Version in the list, and on this Version object you can call your getLabel method.
However, the real question here is, what index do you need? Or, put otherwise, are there multiple objects in the versions list? Because if not, you are overcomplicating things for yourself here.

Because form.getVersions() will returns List<Version> so you can't call below code:
wsForm.setVersionLabel(form.getVersions().getLabel());
If you want you can use following:
wsForm.setVersionLabel(form.getVersions().get(yourIndex).getLabel());// change index for object which you want
Note: You have to make sure which Version object's label you want to set in wsForm, In the example its just setting for first object. And make sure form.getVersions() is not null nor empty.
For last element
form.getVersions().get(form.getVersions().size()-1);

Based on your comments, that your versions increase every time someone modifies your form and if you want to get the version label of the most recent edit, you can do something like this.
int recentIndex = form.getVersions().size()-1;
wsForm.setVersionLabel(form.getVersions().get(recentIndex).getLabel());
As you're adding versions to list, the most recent version is the last version in your list, so get the label from that version

Related

How to update the value of a class instance in a ArrayList

ArrayList<Staff> allStaffs = new ArrayList<>();
allStaffs.add (new Staff("Jason", 1, "012323787", 987, 2300, "Computers"));
I want to update one of the fields in that instance. Like the name "Jason".
I kept figuring this out for myself but to no avail and also tried looking for other forums.
One possibility (probably not the most efficient) is to iterate through the list until you find the instance you want to update:
for(Staff staff : allStaffs){
if (staff.getName().equals("Jason")){
// here "staff" is that instance:
// staff....
}
}
If you know which element to change in the arraylist, simple get that elemnet as below and do something like this;
allStaffs..get(0).setName(0,"newJason")
Here 0 represents the index value of the element that needs to be changed.
This code is assuming that the Staff class contains a method called setName, and that "Jason" is being set as the name property of that Class.
Also, for future reference, when you say
"...I kept figuring this out for myself but to no avail and also tried looking for other forums."
It is always best to give an example of what you tried and what research was done by you. Also, it would be good if you share more of your code, like perhaps the Staff class which is what you are basically trying to change.
Hope you liked my answer. Please give a vote up if you did! :)

Java: Wrapping objects in some type of collection to store duplicates in a set

I want to make a set of some type of collection (not sure which one yet) as a way of "storing duplicates" in a set. For example if I wanted to add the integer 5 with 39 additional copies I could put it into an arraylist at index 39. Thus if I were to get the size of the arraylist, I would know how many copies of 5 existed within the set.
There are a few other ways I could implement this but I have yet to decide on one. The main issue I'm having with implementing this is that I'm not sure how I can "dynamically" make arraylists (or whatever collection I may end up using) so that whenever someone were to call mySet.add(object), the object is first inserted into a unique arraylist then into the set itself.
Can anyone give me some ideas on how I could approach this?
EDIT:
Sorry I should have been more clear in my question. The point of the code that I'm writing is that we have a set-like collection that allows duplicates. And yes some of the associated methods will be re-written/will have to be re-written. Also my code should be written under the assumption that we do not know what type of object is being inserted(only one data type per set though) nor how many instances of the same object will be added nor how many different unique objects will be added.
I would rather go for using a Map like
HashMap list <Object, Integer>
where Object is the Object that you want to count and Integer is the count
You could try guava's MultiSet, I think it's what you want.
It can store the count of each object. What you need to do is just
multiSet.put(object);
And if it is put for the first time, like you said, a new list will be created, or its count will added by one.

Get and Set methods in Sets

List interface allows us to get the object using get() method at an index.
How can we obtain the object at the particular index in set interface like LinkedHashSet
Set is unordered. There isn't the concept of index.
Therefore, if you want to get a particular element, you are forced to loop over it and break as soon as you find element you wanted.
http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
and here: http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html
But a set is only used to check if something is in the list, not where it is.
Short answer is, it is not possible. However, you can get an array that has all datum from the Set you are using and then accessing it via an index. This has to do with the abstraction provided by Set which is different from List.
A Set is simply a collection that does not allow duplicates (no comments on ordering), but a List is a collection that implies ordering, so each value has an associated index.
You can't. There is no indexed acces for a set since it is not ordered.

Get the index of an object I just added to an ArrayList in Java/Android

I want to load a series of objects to an ArrayList, and return the index of where it was added so it can be used later directly from the ArrayList. It'd be akin to me loading a set of 5 frames for a graphic and calling the data for frame 3 directly from the list.
Upon looking around at a couple potential posts that may be related, I found something that was related, and made me wonder. Is there even a built in function to GET the index of a recently added object?
The link I am looking at that made me think of this was: ArrayList indexOf() returns wrong index?
Basically, the way I was looking at it was that I would do something along the lines of the following psuedocode:
private ArrayList<FrameData> mylistofframeshere = new ArrayList();
FrameData Framenumberone = new FrameData(constructorblah goes in here);
int wherediditgo = mylistofframeshere.add(Framenumberone);
Or I thought I could do something along the lines of
mylistofframeshere.getindex(Framenumberone);
My backgrounds in coding are more procedural based at this point, so I am more used to knowing what the index is, just in order to place the data to begin with. I looked around at the oracle documentation as well, with findings something similar to the above link. Any suggestions??
EDIT : I'm going to add some extra clarification in here, because I really didn't put enough effort into the example and explanation.
Another example of trying to use something like a direct index of a list would be if I had a set of tiles I wanted to use as terrain for a game or something. I would load a set of possible tiles for the area into a central ArrayList. Upon trying to place these tiles, I would just reference the pre-loaded object I have in my ArrayList in order to draw the appropriate bitmap/whatever.
I'm still a bit new to Java, so I'm willing to bet it's just something simple I'm overlooking in the mechanics of using these datatypes. I'll keep editing this until I get the explanation right.
When you add something to an ArrayList, it goes to the last available space. In other words:
List<FrameData> list = new ArrayList<FrameData>();
list.add(frame1);
FrameData frame = list.get(list.size() - 1); //frame == frame1
But I wonder why you would need to do that. If you explain more about what you are trying to achieve, there might be a different / better way to get to the same result.
There is a method like ArrayList.indexOf(object); , Try using that method to get index of the object
It all depends on what you want to use the index for. If you simply need to map each element in your list to a key so you can later retrieve the element with the key, you should perhaps consider using a HashMap. If you are more concerned with the ordering, you can use a List. As someone already answered, the index with be incremented as you add elements into the list. If you know the total number of frames you will have before hand, you can initialize an ArrayList by passing in the size as an argument to its constructor, then add each frame by manually specifying the index with list.add(0...size-1, element).
In short,
If you simply want to store and retrieve by your own key /
incremented key -> use a HashMap.
If ordering is important, use a list.
Instead of using ArrayList in this way, you can use a Map<Integer,FrameData>. you can replace Integer with anything which might fit better in your project.

Java ArrayList.remove() not decrementing the Size of the ArrayList

I have an ArrayList to store some data, but whenever I remove an item from the list, the size does not decrease, even when I call ArrayList.trimToSize(). This is causing me nullPointerExceptions.
How can I remove a single item from an ArrayList and have the list's size() shrink accordingly?
EDIT: All right, here's the code. Here's a bit of background you'll need to know, since I can't post all the code. I have an ArrayList called _dataHeap and a HashMap called _dataMap. The ArrayList is a binary Heap containing a "findable" object, which has a Key. The HashMap bind from a Key to the index of the object in the ArrayList. This is so an item in the queue can be found by item using the HashMap or by index using ArrayList. The Key can be any Object, as long as it is unique for every item in the queue.
I've debugged this line by line, and the Heap contains the object, even down to the Hashcode. The problem is, the Object is never being removed from the ArrayList. This must mean that _dataMap.get(element.getKey()) is not pointing to where it should. I've checked it though, I used a test object outside of my implementation that maps from a String to a custom object with String as a Key.
I make one object, with String "one" as its key. I insert it, then try to remove it. I've stepped through this, and everything checks out, except one thing: The object is never removed from the queue. It's got the same Hashcode, the same Key, everything. It gets removed from the map just fine, but not from the ArrayList.
Here's the remove method:
public T remove(T element) {
//We'll need this data to return the proper value
T t = _dataHeap.get(_dataMap.get(element.getKey()));
/*
* this Swap() call is used to swap our target with the end
* of the arraylist. This means that whenever we remove it,
* we don't have a change in indexes of the other nodes.
* After that, we downHeapify() to fix the whole graph back
* to it's functional state.
*/
swap(_dataMap.get(element.getKey()),length()-1);
//Remove from the Heap
_dataHeap.remove(_dataMap.get(element.getKey()));
_dataHeap.trimToSize();
//Remove from the Map
_dataMap.remove(element.getKey());
downHeapify();
return t;
I hope this gives you a better idea of what I'm doing wrong.
EDIT THE SECOND: Holy crap I finally fixed it! I pulled the _dataHeap.get(element.index) into it's own variable. That solved EVERYTHING!
As Bemace said, check if remove works as you intend. I'd bet money that your equals() method on the object you're composing doesn't work how you'd expect it to, because you did not override it.
Furthermore, after you override equals, take care to also override hashCode. It'll save you a SO question when your object doesn't work with HashMaps. :)
A tip: Look into using JUnit. It will blow these little errors right out of the water, making it obvious to you when something's not working how you'd hope. It's very hard to ignore a bright red spot on your beautiful green bar.
Sounds to me like you're not actually removing anything. What's the return value of your remove call?
If you're using remove(int) the return value should be non-null. If using remove(Object), the result should be true. Otherwise you haven't actually removed anything. Attempting to remove an element which doesn't exist is not an error, just returns null or false.

Categories