I need to store objects using iterator but I found just the last element, what do you think ?
if (links.size()>0) {
for (Iterator<Link> iterator = links.iterator();
iterator.hasNext();) {
Link link = (Link) iterator.next();
item.setLink(link);
objects.add(item);
}
}
In objects, I pass to item and I found the last link, so what should I do? This idea will work item.setLink( list of links); or not?
It's difficult to tell what you're trying to achieve as the code has several problems:
you're setting the link in the class object in each iteration which is why only the last element remains (this is assuming the .setLink() method doesn't do anything funky inside)
if your objects collection (is it a collection?) is a Set and the item hashCode method computes its value based on the link value only your elements will be replaced
It's a guess only but perhaps this is what you're trying to do?
for (Link link : links) { // works only if your collection is properly typed
MyClass item = new MyClass();
item.setLink(link);
objects.add(item);
}
A couple of other suggestions:
use an enhanced for loop (as shown above)
the if (links.size()>0) { line is redundant -- your loop will simply do nothing if the collection is empty
Related
So I have this method, it not complete because cannot get it work with the set that I have. The set that have has {0,1,2,7,8,9,10}.
I tried with an if/else, but it gave me nullpointer exception error.
Should I put HashSet objects into an array and then compare the objects?
Please provide any insight.
This is customer intersection method, where I have been provided HashSet.java file which contains, the these following methods.
1 - add method
2 - contains method
3 - remove method
public HashSet Intersect(HashSet s1)// only 1 & 2 should be printed
{
HashSet intersect = new HashSet(buckets.length);
Iterator iter = this.iterator();
while(iter.hasNext())
{
intersect.add(iter.next());
}
Iterator iter1 = s1.iterator();
while(intersect.contains(iter1.next()))
{
intersect.remove(iter.next());
}
return intersect;
}
For your NPE issue you should first read about iterators. Indeed you must always check if there is a next element via .hasNext() (if true then you may safely call .next()). Secondly and tightly related your logic is invalid and problems happen quickly in second loop as you call iter.next() while you 've already fully iterated over iter. So the next element is obviously null. This is certainly not what you intended to code.
Can someone suggest me a datatype/structure in java that satisfies:
1) no fixed size
2) does not automatically sort data. Data should be stored in the order in which it arrives
3) it should store only unique entries
4) its elements are accessible or atleast the first element should be!
links are not able to maintain unique entries.
I tried working with Sets but it changes the order of my data automatically which i dont want to let happen.
So i am now trying to work my way with LinkedHashSet, but I am not able to find the exact way to access the first element of the same for comparision.
Any suggestions please. Thanks!
You can use LinkedHashSet if you don't wanna write your own structure. Getting elements may be kinda tricky, try this:
Integer lastInteger = set.stream().skip(set.size()-1).findFirst().get();
This is gonna get the last element, if you want different elements you need to skip a different count. This is only one of the ways, you can get an iterator and iterate yourself etc. Remember to override hashCode and equals when working with sets.
LinkedHashSet is the right data structure for your requirements.
You can access the first element like so:
Set<String> set = new LinkedHashSet<>();
set.add("a");
set.add("b"); // And so on
// Retrieve first element
// Will throw NoSuchElementException if set is empty
String firstElement = set.iterator().next();
// Retrieve and remove first element
Iterator<String> i = set.iterator();
String otherFirstElement = i.next();
i.remove();
For accessing other elements, see answer from #Whatzs.
If I properly understand your question, you are looking for a data structure that would combine the properties of a Set and an ArrayList, a kind of "ArraySet".
I haven't found anything in the core java for that but it looks like the Android JDK has such a data structure.
https://developer.android.com/reference/android/util/ArraySet.html
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/util/ArraySet.java
One solution might be to build your own based on the android implementation.
Is it possible to remove an object other than the current when iterating?
List<GameObjects> gameObjects = new ArrayList<GameObjects>();
ListIterator<GameObject> iterator = gameObjects.listIterator();
while (iterator.hasNext()) {
iterator.next().update();
// Here I would like to do gameObjects.remove(other_object_in_gameObjects);
}
Obviously that's not allowed. But can an Iterator do it somehow? Or is it not doable at all?
Don't know what other_object_in_gameObjects is, but you can create a temp List recording the list items that needs to be deleted, and after the iteration remove all the items in the tempList that are also in gameObjects.
You might look into using the Guava library. There is an Iterables.removeIf method that allows you to remove all objects from a list that match your criteria.
There's an example of usage at this other SO question.
I have a class which holds a linked list of Item objects. I want this class to hold the "current" Item somehow so I can refer to it in other parts of the program. Is the best way to do this to create a Item object within my class and set it equal to the "current" Item when I wish to set it?
as such:
for(int i = 0; i < [LinkedListofItems].length(); i++)
{Item currentItem = [LinkedListofItems].getAt(i); break;}
And then if I would like to set and Items attributes equal to anothers I would override the = operator?
You have to implement an iterator on the LinkedList.
Iterator listIterator = LinkedListOfItems.iterator();
//Use iterator here to access a particular list element by calling .next()
Item itemToStore = listIterator.next();
A few things:
A) From your code example and from what you asked, they seem to be saying two different things. First I would suggest an ArrayList if you will be needing to iterate frequently and if you are not adding and deleting a lot from said list.
B) I am also unsure why you are iterating from your example. If you have an Item that needs to be set for I, you can just use elementAt() method.
C) Also, you must implement an Iterator to traverse the list.
Iterator linkedListIt = LinkedList.iterator();
Now you can go through and what you need, and grab the current object if you need with LinkedList.next();
Is there any way by which I can avoid using get(0) in the list iteration ?
Its going to be always risky using get(0) while iterating over a list.
I know for sure that in this list I just have one object.
(P.S. I remember my last manager always saying to me to avoid using get(0) on list iteration.)
It's not really clear what you mean by "risky" but you might consider using Guava's Iterables.getOnlyElement:
List<String> foo = getListFromSomewhere();
String bar = Iterables.getOnlyElement(foo);
This makes it clear that you expect there to be one and only one element. If you think there may be no elements, you can use the overload which allows you to specify a default value.
That way your expectations are checked when you ask for the element... but it's not obvious what else you're looking for. (You remember your last manager warning you about this - but do you remember why he warned you?)
Edit: I misuderstood the question, not realizing there was only a single item in the List. While my options still work, they aren't really necessary. However, I question the danger of using get(0) if your precondition is that there is a list with a single element.
You have a few options:
First is simply let the loop get the object for you with a for-each loop
for(Object thing : things)
Second, is convert the list into another form and access it in the appropriate manner:
Object[] thingArray = things.toArray();
for(int i = 0; i < thingArray.length; i++)
Third is to use the ListIterator
ListIterator<Object> thingIterator = things.listIterator();
while(thingIterator.hasNext())
{
Object thing = thingIterator.next();
Object objOne = list.iterator().next();