How do I get the Intersection method to work? - java

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.

Related

Iterator Java to store object

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

How to avoid using get(0) in list iteration

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();

Iterator behavior in Java

I have a question regarding the iterator behavior in Java.
I have a call such as this:
myIterable.iterator().hasNext()
If this call returns true, can I be sure that the collection has at least two elements?
From the Java API specification, I could only find out that true means there is one more element to go which can be reached by next(). But what happens if the pointer is at the very beginning (meaning whether the hasNext() can recognize the first element separately)
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator.html
it says true if the iteration has more elements. But more element could also mean the very first one?
[Edit]
How can I know whether the iterator has exactly two elements to iterate through? Of course, I can iterate and count, but I can't go back or iterate twice or clone the iterator in my case, this is an Hadoop iterator.
it can mean the first one. You can only be sure that it has more than zero element
hasNext() returning true or false makes you able to discern between zero items and one-or-more (at the start of the iteration that is).
You want to know whether it has two-or-more, without starting the iteration. I think, basically, you can not. Exposing that information is more than an iterator has to do: make available the next and only the next item (and information about whether this item exists).
Possibly, the iterator itself doesn't even have that knowledge yet!
But of course you are free to memorize the items you already took out of the list. Then you could use them later, once you know there's actually two or more items in the list.
If you need to pass the iterator to other code, you could write your own class that implements iterator, internally remembers the first two items as member variables and hands out those first, then continues to iterate over the rest of the items in the original iterator (if there's any more left) - a reference to the original iterator therefore also needs to be stored in your custom made iterator
Java iterators are positioned before the fist element. What your expression myIterable.iterator().hasNext() shows is that there is at least one element.
hasNext tells you there is another element accessible with next().
So it just mean you have at least one element.
If myIterable.iterator().hasNext() returns true it means there is at least one element and you can use next() to access that.
How can I know whether the iterator has exactly two elements to iteratte through? Of course, I can iterate and count, but I can't go back or iterate twice or clone the iterator in my case, this is hadoop iterable.
There is no way to do this. Maybe an iterator is wrong for your scenario.
No. If hasNext() returns true means, that collection having atleast one element because the origin position of iterator should before the first element.
List l = new ArrayList();
l.add(1);
Iterator it = l.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Result will be 1 because origin position of iterator should before the first element. When we check it.hasNext() for the first time, it will return true because it is having one element. Then, print the element using it.next(). Now only, iterator in the first position. When we check it.hasNext() for the second time, it will return false.
In the iterator, it has a field named cursor.This cursor init value is the collection object size.When you call the method next(), it will --. The method hasNext() check the cursor is equals to zero.Its zero return false, else return true.
But the list and map is not the same, their difference is the concrete realization, the original is the same.List check size, map check end node.

JAVA - loop a linkedlist/ find a string in linkedlist

high, how do i loop through a linked list. i need to write a method find(), that returns true if a certain string is in the list
public boolean find( Stack<String> s, String key )
{
for( String item : s )
{
if( item.equals( key ) )
return true;
}
return false;
}
Typically, you have a pointer to the head of the list. You check for whether the pointed-to item matches your search string. If it does, you return true. If not, you move your pointer to the next item in the list. If you reach the end of the list, you return false.
(I'm assuming this is homework, so I won't actually write the code. If you show us some non-working code, we'll help you make it work.)
Edited to add: If you're working with a linked list, why are you passing in a stack? Anyway, the code you've posted looks like it should work. You should probably post the code you're using to set up the data and call the find method; there may be a problem there.
The error you mention sounds like maybe you aren't passing a Stack correctly; you should be able to do a foreach loop on the contents of a Stack.
There's already a "contains" method:
http://download.oracle.com/javase/6/docs/api/java/util/LinkedList.html#contains(java.lang.Object)
If your LinkedList elements are only Strings, it should work OK. Otherwise you'll need to override the 'equals' method of your model.
It sounds like you're saying that you're implementing a custom linked list implementation called Stack, and you're having looping over your list using for-each syntax. In order to use that syntax, your class needs to implements the Iterable interface. This means you will need to create an Iterator for your list as well, which will provide next(), hasNext(), and remove() methods

Whats the replacement of For-Each loop for filtering?

Though for-each loop has many advantages but the problem is ,it doesn't work when you want to Filter(Filtering means removing element from List) a List,Can you please any replacement as even traversing through Index is not a good option..
What do you mean by "filtering"? Removing certain elements from a list? If so, you can use an iterator:
for(Iterator<MyElement> it = list.iterator(); it.hasNext(); ) {
MyElement element = it.next();
if (some condition) {
it.remove();
}
}
Update (based on comments):
Consider the following example to illustrate how iterator works. Let's say we have a list that contains 'A's and 'B's:
A A B B A
We want to remove all those pesky Bs. So, using the above loop, the code will work as follows:
hasNext()? Yes. next(). element points to 1st A.
hasNext()? Yes. next(). element points to 2nd A.
hasNext()? Yes. next(). element points to 1st B. remove(). iterator counter does NOT change, it still points to a place where B was (technically that's not entirely correct but logically that's how it works). If you were to call remove() again now, you'd get an exception (because list element is no longer there).
hasNext()? Yes. next(). element points to 2nd B. The rest is the same as #3
hasNext()? Yes. next(). element points to 3rd A.
hasNext()? No, we're done. List now has 3 elements.
Update #2: remove() operation is indeed optional on iterator - but only because it is optional on an underlying collection. The bottom line here is - if your collection supports it (and all collections in Java Collection Framework do), so will the iterator. If your collection doesn't support it, you're out of luck anyway.
ChssPly76's answer is the right approach here - but I'm intrigued as to your thinking behind "traversing through index is not a good option". In many cases - the common case in particular being that of an ArrayList - it's extremely efficient. (In fact, in the arraylist case, I believe that repeated calls to get(i++) are marginally faster than using an Iterator, though nowhere near enough to sacrifice readability).
Broadly speaking, if the object in question implements java.util.RandomAccess, then accessing sequential elements via an index should be roughly the same speed as using an Iterator. If it doesn't (e.g. LinkedList would be a good counterexample) then you're right; but don't dismiss the option out of hand.
I have had success using the
filter(java.util.Collection collection, Predicate predicate)
method of CollectionUtils in commons collections.
http://commons.apache.org/collections/api-2.1.1/org/apache/commons/collections/CollectionUtils.html#filter(java.util.Collection,%20org.apache.commons.collections.Predicate)
If you, like me, don't like modifying a collection while iterating through it's elements or if the iterator just doesn't provide an implementation for remove, you can use a temporary collection to just collect the elements you want to delete. Yes, yes, its less efficient compared to modifying the iterator, but to me it's clearer to understand whats happening:
List<Object> data = getListFromSomewhere();
List<Object> filter = new ArrayList<Object>();
// create Filter
for (Object item: data) {
if (throwAway(item)) {
filter.add(item);
}
}
// use Filter
for (Object item:filter) {
data.remove(item);
}
filter.clear();
filter = null;

Categories

Resources