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
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.
Is there a simple method to check if an element is contained in an iterable or iterator, analogous to the Collection.contains(Object o) method?
I.e. instead of having to write:
Iterable<String> data = getData();
for (final String name : data) {
if (name.equals(myName)) {
return true;
}
}
I would like to write:
Iterable<String> data = getData();
if (Collections.contains(data, myName)) {
return true;
}
I'm really surprised there is no such thing.
In Java 8, you can turn the Iterable into a Stream and use anyMatch on it:
String myName = ... ;
Iterable<String> data = getData();
return StreamSupport.stream(data.spliterator(), false)
.anyMatch(name -> myName.equals(name));
or using a method reference,
return StreamSupport.stream(data.spliterator(), false)
.anyMatch(myName::equals);
Guava has the functions Iterables.contains and Iterators.contains which do what you want. You can look at the source to see how to implement them yourself.
An iterator is a sort of cursor which can be moved over the elements of any collection of elements. So its inner state is mainly the pointer to the current element. If you would try to find out whether it "contains" a certain element you would have to move the cursor and therefore modify the inner state. Modifying the state by simply asking a question is surely a bad thing to do.
That is even the problem with the mentioned Guava. It will modify the iterator object by simply calling the contains method.
An iterable on the other hand is simply an interface telling the compiler that there is something to iterate over. In most cases the iterable object will be the collection itself. If you would add methods like "contains" to the interface Iterable you would get a (simplified) version of the Collection interface - which already exists. So there is no need for that.
If you are stuck in your code at some place where you have a reference to an iterable but need functionality of a collection you should think about refactoring your code. Either you should use the interface collection consistently or ask yourself why you should better not call collection methods at this point. So your problem is most probably a result of a suboptimal code design.
On the other hand I would consider it to be a strange thing to use Iterable as type for parameters or variables anyway. Technically you can do this but I think it is meant to be used in loops only.
From the JavaDoc for Iterable:
Implementing this interface allows an object to be the target of the "foreach" statement
I'm sorry to say what you're trying to do is impossible.
.contains is a method of the interface Collection and not Iterable so maybe you can use that interface.
An Iterator is like a pointer/reference to an element in a collection. It is not the collection itself. So, you can't use iterator.contains(). Also, an Iterable interface is used to iterate over a collection using a for-each loop. A collection and Iterator / Iterable are different.
I have a custom ArrayList interface that extends the Comparable class and is in ascending order. The class I'm working on is implementing this interface.
My problem is I need to edit the add method so that it will add an element to the ArrayList, have the List stay ordered, and make sure there are no duplicates.
It would be easy to do all this in separate methods, but that's out the question. I need the one method to do it all, so that when the method is called, (as long as it isn't a duplicate) the element is added in the correct position.
On top of that, to check the position of the index to insert the method to, I must use the compareTo() method inherited from the Comparable class. Only problem is I have to implement my own compareTo() method in the class I'm working on. I've looked all over, and I'm confused on how to go about that for this certain class.
Here's my code so far:
public void add(E item) throws IndexOutOfBoundsException {
if (contains(item)) {
throw new IllegalArgumentException("This is a duplicate!");
}
//here is where I need the implementation to add the item to the array, in order
}
Then here is my compareTo() method:
public int compareTo(E item) {
if () {
return -1;
}
else if () {
return 1;
}
else {
return 0;
}
}
One way to do this is to first check if
myArrayList.contains(item)
and then if not, just insert and re-sort your array:
myArrayList.add(item);
Collections.sort(myArrayList);
Note that in general, if you want to maintain a sorted set without duplicates, there are better data structures than ArrayList.
What about a TreeSet? It seems to have the behaviour you're looking for.
You don't give that much information. If what you truly are implementing is an ArrayList like data structure, then you first need to see if the array is large enough to add a new item. If not, you need to create a new array. In the first case, you need to find the location to enter the new element, shift everything from that position on down one, and then add the element. For the second case, you can "merge" the old list with the new element (that is, keep adding from the old list until the location where the new element should go comes up, add the new element, and continue). Another question I have: where is the compareTo(Object o) being put? If you are putting in the ArrayList class, that's rather pointless since you don't really want to compare arrays. If it's in the class being stored in the ArrayList, you want to return -1 if the this object comes before the object passed in, a -1 if the this object comes after, and 0 if they are equal. If you can choose your data structure, you might want to consider a linked list: they are very easy to add to and remove from.
If you are extending the ArrayList class, then this is super (pun intended) easy. In your add method, you have to determine the location to add the element, then call the super.add(int loc) method
Adding an element in the right position is the same as failing to do binary search and recording the last position you compared.
Check out the documentation for Arrays.binarySearch. Hopefully this will give enough information to implement it. Your implementation of comparable should just be the same as you would use for sorting. Here's the relevant excerpt from the documentation:
index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
If I have an ArrayList of String forming part of a class in Java like so:
private ArrayList<String> rssFeedURLs;
If I want to use a method in the class containing the above ArrayList, using ArrayList contains to check if a String is contained in this ArrayList, I believe I should be able to do so as follows:
if (this.rssFeedURLs.contains(rssFeedURL)) {
Where rssFeedURL is a String.
Am I right or wrong?
You are right. ArrayList.contains() tests equals(), not object identity:
returns true if and only if this list
contains at least one element e such
that (o==null ? e==null : o.equals(e))
If you got a NullPointerException, verify that you initialized your list, either in a constructor or the declaration. For example:
private List<String> rssFeedURLs = new ArrayList<String>();
Yes, that should work for Strings, but if you are worried about duplicates use a Set. This collection prevents duplicates without you having to do anything. A HashSet is OK to use, but it is unordered so if you want to preserve insertion order you use a LinkedHashSet.
You are right that it should work; perhaps you forgot to instantiate something. Does your code look something like this?
String rssFeedURL = "http://stackoverflow.com";
this.rssFeedURLS = new ArrayList<String>();
this.rssFeedURLS.add(rssFeedURL);
if(this.rssFeedURLs.contains(rssFeedURL)) {
// this code will execute
}
For reference, note that the following conditional will also execute if you append this code to the above:
String copyURL = new String(rssFeedURL);
if(this.rssFeedURLs.contains(copyURL)) {
// code will still execute because contains() checks equals()
}
Even though (rssFeedURL == copyURL) is false, rssFeedURL.equals(copyURL) is true. The contains method cares about the equals method.
Perhaps you need to post the code that caused your exception. If the above is all you have, perhaps you just failed to actually initialise the array.
Using contains here should work though.
Your question is not very clear.
What's your code exactly doing? Give more code.
What's the error you're getting?
You say you get a null-pointer. You cannot get a null pointer as a value returned by contains().
However you can get a NullPointerException if your list has not been initialized. By reading your question now, I'd say that what you show here is correct, but maybe you just didn't instantiate the list.
For this to work (to add a feed URL if it isn't already in the list):
if (!this.rssFeedURLs.contains(rssFeedURL)) {
this.rssFeedURLs.add(rssFeedUrl);
}
then this declaration would do:
private ArrayList<String> rssFeedURLs = new ArrayList<String>();
or initialize your list later on, but before trying to access its methods:
rssFeedUrls = new ArrayList<String>();
Finally... Do you really need a List? Maybe a Set would be better if you don't want duplicates. Use a LinkedHashSet if preserving the ordering matters.
Right...with strings...the moment you deviate from primitives or strings things change and you need to implement hashcode/equals to get the desired effect.
EDIT: Initialize your ArrayList<String> then attempt to add an item.
You're correct. As others said according to your comments, you probably did not initialize your ArrayList.
My point is different: you claimed that you're checking for duplicates and this is why you call the contains method. Try using HashSet. It should be more efficient - unless you need to keep the order of URLs for any reason.
Thanks to you all for answering so quickly. I could always use a set but I have the ArrayList working now. The problem was that in the constructor of the class containing the ArrayList, I was not saying:
public RSS_Feed_Miner() {
...
this.rssFeedURLs = new ArrayList<String>();
...
}
D'Oh! for a Friday afternoon.
ArrayList<String> newlyAddedTypes=new ArrayList<String>();
.....
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test2");
if(newlyAddedTypes.contain("test"){
//called here
}
else{
}
In C+ one can use iterators for writing to a sequence. Simplest example would be:
vector<int> v;
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
*it = 42;
}
I need something more complicated - keep iterator as a class member for a later use.
But I don't know how to get this behavior from Java iterators.
Are there writable iterators in Java at all?
If not then what replaces them?
The ListIterator (which you can obtain by List#listIterator()) has add() and set() methods which allows you to respectively insert and replace the item at the currently iterated index. That's as far the only "writable iterator" as I can think of in Java.
Not sure though if that is the exact replacement of the given C++ code since I don't know C++.
As arrays can be accessed directly and quickly by their index, you don't really need an iterator object. Wouldn't it be enought to save the index of the array in that class member? This would permit to read and write the value of the array.
PS: You could use an ArrayList, which is an automatically growing set of arrays and use the ListIterator as Balus described in order to use the iterator-object-approach.
Looks more like you want a List (or maybe some other collection, like Set) or an array.
Also, you could just make your contents mutable. It looks silly for integers, but continuing your example
for (MutableInteger i : CollectionOfMInts) i.setTo(42);