I am creating a demo shopping cart in android for this i am using Application class for saving data. I am unable to delete data from linkedlist. I am calling removeItem() function for android activity for removing selected item from the list but it is not working any one can help me.
package in.co.santoshsharma.bookshopping;
import java.util.LinkedList;
import android.app.Application;
import android.content.res.Configuration;
public class GlobalData extends Application{
private String email;
private String itemName;
private int itemQuantity;
private int itemCost;
public GlobalData(){
}
public GlobalData(String iName,int iQunt,int iCost) {
// TODO Auto-generated constructor stub
this.itemCost=iCost;
this.itemName=iName;
this.itemQuantity=iQunt;
}
public void setEmail(String mail)
{
this.email=mail;
}
public String getEmail()
{
return email;
}
public String getItemName()
{
return itemName;
}
public int getItemCost()
{
return itemCost;
}
public int getItemQunt()
{
return itemQuantity;
}
LinkedList<GlobalData> list = new LinkedList<GlobalData>();
public void setList(String iName,int iQunt,int iCost)
{
list.add(new GlobalData( iName, iQunt, iCost));
}
public LinkedList<GlobalData> getList()
{
return list;
}
public void removeItem(String iName,int iQunt,int iCost)
{
for(GlobalData data:list)
{
if(data.getItemName().equals(iName))
{
list.remove(itemName);
//list.remove(iCost);
//list.remove(iQunt);
}
}
}
}
First, override equals() method and use itemName attribute for the comparison
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (itemName == null) return false;
if (o instanceOf String) return itemName.equals(o);
else if (o instanceOf GlobalData) return ((GlobalData) o).itemName.equals(this.itemName);
else return false;
}
Then, change your removeItem() method
public void removeItem(String iName) {
list.remove(iName);
// or uncomment line below to completely remove all matching elements
// for (;;list.remove(iName)) {}
}
According to http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html#remove(java.lang.Object) remove() method of a LinkedList will call the equals() method of the supplied Object and compare it with every element in the list.
Hope this helps :)
you cannot operate in lists (add, remove... items) while you iterate on them. You have to use an Iterator
for(Iterator<EmpDedup> iter = list.iterator(); iter.hasNext();) {
EmpDedup data = iter.next();
if (data.getRecord() == rec1) {
iter.remove();
}
}
see http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html
Refered from https://stackoverflow.com/a/10735435/1602230
Use a iterator to remove the element:
public void removeItem(String iName, int iQunt, int iCost) {
Iterator<GlobalData> iterator = list.iterator();
while (iterator.hasNext()) {
GlobalData data = iterator.next();
if (data.getItemName().equals(iName)) {
iterator.remove();
}
}
}
- You are Concurrently accessing and modifying the Collection, that can't be done from For-Each loop directly..
- Use Iterator to solve this problem.
LinkedList<GlobalData> q1 = new LinkedList<GlobalData>();
Iterator<GlobalData> iterator = q1.iterator();
while (iterator.hasNext()){
GlobalData mp = iterator.next();
if (mp.name.equals("xyz")){
iterator.remove(); // You can do the modification here.
}
}
You cannot modify a Collection using for-each loop. Use simple for loop or while.
The for-each loop hides the iterator, so you cannot call remove.
Therefore, the for-each loop is not usable for filtering. Similarly it
is not usable for loops where you need to replace elements in a list
or array as you traverse it.
Source: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
Generally, a collection named list storing elements of type E uses an iterator in the following way:
Iterator<E> iterator = list.iterator();
while(iterator.hasNext()) {
<do something with iterator.next()>;
}
Related
I am currently trying to implement Iterator which receives a collection and a char and that yields the
Strings that starts with that char.
So I ended up with the following (working) code:
class A {
public static void main (String [] args) {
String [] arr = {"abcd","gr","gres","bvg","bb"};
class FirstCharIt implements Iterator<String> {
char c;
private Iterator<String> it;
public FirstCharIt (Collection<String> lst,char c) {
this.c = c;
this.it = lst.stream().filter(x->{
return (x.charAt(0)==this.c);
}).iterator();
}
#Override
public boolean hasNext() {
return it.hasNext();
}
#Override
public String next() {
return it.next();
}
public Iterator<String> get () {
return it;
}
}
FirstCharIt it1 = new FirstCharIt(Arrays.asList(arr),'b');
for (it1.get();it1.hasNext();) {
System.out.println(it1.next());
}
}
}
Although this code is working this is not actually implementing Iterator interface and I even can remove the 'implements Iterator' from my class headline.
And of course the method get wasn't there in more right implementation
So I would like to have some advice about what I did here,
thanks
Filter the input list at initialization, have that filtered collection and an index as fields of your iterator.
Have hasNext() check if the index has reached the end of the filtered collection, and next() increase the index and return the element it previously pointed at.
static class FirstCharIt implements Iterator<String> {
private int currentIndex;
private List<String> filtered;
public FirstCharIt (List<String> coll, char letter) {
this.filtered = coll.stream().filter(x->x.startsWith(""+letter)).collect(Collectors.toList());
this.currentIndex = 0;
}
#Override
public boolean hasNext() {
return currentIndex < filtered.size();
}
#Override
public String next() {
if (!hasNext()) { throw new NoSuchElementException(); }
return filtered.get(currentIndex++);
}
}
You can try it here.
I am trying to add patient records into a queue and then display all the records on the screen but I am not getting them.. I guess the display method isn't working for me.. I probably made a mistake.. Here is my code for queue of the patients.
public class Patient_Queue {
private LinkedList list;
public Patient_Queue()
{
// Create a new LinkedList.
list= new LinkedList();
}
public boolean isEmpty()
{
return (list.size() == 0);
}
public void joinQueue(Object item)
{
list.add(item);
}
public Object Consultation()
{
Object item = list;
list.remove(0);
return item;
}
public void display() {
for(int q=0;q<list.size();q++)
{
System.out.println(list.get(q));
}
}
public int size(){
return list.size();
}
public void clear()
{
list.clear();
}
}
It seems to be a mistake here:
public Object Consultation()
{
Object item = list;
list.remove(0);
return item;
}
Corrected version:
public Object Consultation()
{
Object item = list.get(0); // fix
list.remove(0);
return item;
}
Note that LinkedList implements Queue interface and you can use its Queue methods directly.
I tried to work this out but couldn't.
I need to implement a class which implements iterator and takes iterator as constructor parameter,
1)Need to return every 2nd hasnext
2)Need to return every 2nd next element
Basically I am trying to make use of given iterator received from constructor, But when i use next element on hasnext I am actually increasing the iterator by one element. so problem comes when i independently access hasNext or next element and does not pass all the test cases. Any solution or idea on this
Template and my expected implementation looks like below:
public class AlternateIterator<T> implements Iterator<T>
public AlternateIterator(Iterator<T> target)
public boolean hasNext() {
boolean returnvalue = false;
if(iterator.hasNext()) {
iterator.next();
returnvalue = iterator.hasNext();
}
return returnvalue;
}
#Override
public T next() {
T object = null;
if(iterator.hasNext()) {
object = iterator.next();
return object;
}
else
return null;
-- Gone through this link but it creates a new implementation itself while i want to use the given template only:
Can we write our own iterator in Java?
Track whether you've skipped the element from the source iterator or not, like this:
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
final class AlternateIterator<T>
implements Iterator<T>
{
static <T> Iterable<T> alternate(Iterable<T> original)
{
return () -> new AlternateIterator<>(original.iterator());
}
private final Iterator<T> source;
private boolean skipped;
AlternateIterator(Iterator<T> source)
{
this.source = Objects.requireNonNull(source);
}
#Override
public boolean hasNext()
{
if (!skipped) {
if (source.hasNext())
source.next();
skipped = true;
}
return source.hasNext();
}
#Override
public T next()
{
if (hasNext()) {
skipped = false;
return source.next();
}
throw new NoSuchElementException();
}
#Override
public void remove()
{
source.remove();
}
}
You need to have a boolean member which stores if hasNext has been called since the last call of next.
This way you know if you need to call an additional next or not in both methods.
Your issue is that hasNext() changes the state of the decorated Iterator. You need a member variable like skipped to track state so that hasNext() won't double-advance and skip two, and your implementation of next() should use this.hasNext(), not iterator.hasNext().
Edit: it'll look something like this:
public class AlternateIterator<T> implements Iterator<T> {
public AlternateIterator(Iterator<T> target) { ... }
private volatile boolean skipped = false;
public boolean hasNext() {
if (!skipped) {
skipped = true;
if (iterator.hasNext()) {
iterator.next();
}
}
return iterator.hasNext();
}
#Override
public T next() {
hasNext();
skipped = false;
return iterator.next();
}
}
How would I instantiate DictionaryADT dictionary in the constructor in this code? Also, If someone could help with the Iterators that would be cool. Lastly, if you could help with the print functions that would be nice.
import data_structures.*;
import java.util.Iterator;
public class ProductLookup {
DictionaryADT<String,StockItem> dictionary;
private int maxSize;
// Constructor. There is no argument-less constructor, or default size
public ProductLookup(int maxSize) {
this.maxSize = maxSize;
}
// Adds a new StockItem to the dictionary
public void addItem(String SKU, StockItem item) {
dictionary.insert(SKU,item);
}
// Returns the StockItem associated with the given SKU, if it is
// in the ProductLookup, null if it is not.
public StockItem getItem(String SKU) {
if (SKU == null)
return null;
return dictionary.getValue(SKU);
}
// Returns the retail price associated with the given SKU value.
// -.01 if the item is not in the dictionary
public float getRetail(String SKU) {
if (!dictionary.contains(SKU))
return (float) -.01;
return getItem(SKU).getRetail();
}
public float getCost(String SKU) {
if (!dictionary.contains(SKU))
return (float) -.01;
return getItem(SKU).getCost();
}
// Returns the description of the item, null if not in the dictionary.
public String getDescription(String SKU) {
if (!dictionary.contains(SKU))
return null;
return getItem(SKU).getDescription();
}
// Deletes the StockItem associated with the SKU if it is
// in the ProductLookup. Returns true if it was found and
// deleted, otherwise false.
public boolean deleteItem(String SKU) {
if (SKU == null)
return false;
return dictionary.remove(SKU);
}
// Prints a directory of all StockItems with their associated
// price, in sorted order (ordered by SKU).
public void printAll() {
Iterator<StockItem> iterator = values();
while (iterator.hasNext())
System.out.println(iterator.next().toString());
}
// Prints a directory of all StockItems from the given vendor,
// in sorted order (ordered by SKU).
public void print(String vendor) {
Iterator<StockItem> iterator = values();
if (dictionary.getItem(SKU).getVendor() == vendor)
System.out.println(tmp.toString());
}
// An iterator of the SKU keys.
public Iterator<String> keys() {
return new ;
}
// An iterator of the StockItem values.
public Iterator<StockItem> values() {
return null;
}
}
Why would it be any different than then way you have done maxSize?
public ProductLookup(int maxSize, DictionaryADT<String,StockItem> dictionary) {
this.dictionary = dictionary;
this(maxSize);
}
// Constructor. There is no argument-less constructor, or default size
public ProductLookup(int maxSize) {
this.maxSize = maxSize;
}
If I have a list containing [alice, bob, abigail, charlie] and I want to write an iterator such that it iterates over elements that begin with 'a', can I write my own ? How can I do that ?
The best reusable option is to implement the interface Iterable and override the method iterator().
Here's an example of a an ArrayList like class implementing the interface, in which you override the method Iterator().
import java.util.Iterator;
public class SOList<Type> implements Iterable<Type> {
private Type[] arrayList;
private int currentSize;
public SOList(Type[] newArray) {
this.arrayList = newArray;
this.currentSize = arrayList.length;
}
#Override
public Iterator<Type> iterator() {
Iterator<Type> it = new Iterator<Type>() {
private int currentIndex = 0;
#Override
public boolean hasNext() {
return currentIndex < currentSize && arrayList[currentIndex] != null;
}
#Override
public Type next() {
return arrayList[currentIndex++];
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
return it;
}
}
This class implements the Iterable interface using Generics. Considering you have elements to the array, you will be able to get an instance of an Iterator, which is the needed instance used by the "foreach" loop, for instance.
You can just create an anonymous instance of the iterator without creating extending Iterator and take advantage of the value of currentSize to verify up to where you can navigate over the array (let's say you created an array with capacity of 10, but you have only 2 elements at 0 and 1). The instance will have its owner counter of where it is and all you need to do is to play with hasNext(), which verifies if the current value is not null, and the next(), which will return the instance of your currentIndex. Below is an example of using this API...
public static void main(String[] args) {
// create an array of type Integer
Integer[] numbers = new Integer[]{1, 2, 3, 4, 5};
// create your list and hold the values.
SOList<Integer> stackOverflowList = new SOList<Integer>(numbers);
// Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
for(Integer num : stackOverflowList) {
System.out.print(num);
}
// creating an array of Strings
String[] languages = new String[]{"C", "C++", "Java", "Python", "Scala"};
// create your list and hold the values using the same list implementation.
SOList<String> languagesList = new SOList<String>(languages);
System.out.println("");
// Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
for(String lang : languagesList) {
System.out.println(lang);
}
}
// will print "12345
//C
//C++
//Java
//Python
//Scala
If you want, you can iterate over it as well using the Iterator instance:
// navigating the iterator
while (allNumbers.hasNext()) {
Integer value = allNumbers.next();
if (allNumbers.hasNext()) {
System.out.print(value + ", ");
} else {
System.out.print(value);
}
}
// will print 1, 2, 3, 4, 5
The foreach documentation is located at http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html. You can take a look at a more complete implementation at my personal practice google code.
Now, to get the effects of what you need I think you need to plug a concept of a filter in the Iterator... Since the iterator depends on the next values, it would be hard to return true on hasNext(), and then filter the next() implementation with a value that does not start with a char "a" for instance. I think you need to play around with a secondary Interator based on a filtered list with the values with the given filter.
Sure. An iterator is just an implementation of the java.util.Iterator interface. If you're using an existing iterable object (say, a LinkedList) from java.util, you'll need to either subclass it and override its iterator function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator instance (which has the advantage of being more broadly used), etc.
Good example for Iterable to compute factorial
FactorialIterable fi = new FactorialIterable(10);
Iterator<Integer> iterator = fi.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
Short code for Java 1.8
new FactorialIterable(5).forEach(System.out::println);
Custom Iterable class
public class FactorialIterable implements Iterable<Integer> {
private final FactorialIterator factorialIterator;
public FactorialIterable(Integer value) {
factorialIterator = new FactorialIterator(value);
}
#Override
public Iterator<Integer> iterator() {
return factorialIterator;
}
#Override
public void forEach(Consumer<? super Integer> action) {
Objects.requireNonNull(action);
Integer last = 0;
for (Integer t : this) {
last = t;
}
action.accept(last);
}
}
Custom Iterator class
public class FactorialIterator implements Iterator<Integer> {
private final Integer mNumber;
private Integer mPosition;
private Integer mFactorial;
public FactorialIterator(Integer number) {
this.mNumber = number;
this.mPosition = 1;
this.mFactorial = 1;
}
#Override
public boolean hasNext() {
return mPosition <= mNumber;
}
#Override
public Integer next() {
if (!hasNext())
return 0;
mFactorial = mFactorial * mPosition;
mPosition++;
return mFactorial;
}
}
This is the complete code to write an iterator such that it iterates over elements that begin with 'a':
import java.util.Iterator;
public class AppDemo {
public static void main(String args[]) {
Bag<String> bag1 = new Bag<>();
bag1.add("alice");
bag1.add("bob");
bag1.add("abigail");
bag1.add("charlie");
for (Iterator<String> it1 = bag1.iterator(); it1.hasNext();) {
String s = it1.next();
if (s != null)
System.out.println(s);
}
}
}
Custom Iterator class
import java.util.ArrayList;
import java.util.Iterator;
public class Bag<T> {
private ArrayList<T> data;
public Bag() {
data = new ArrayList<>();
}
public void add(T e) {
data.add(e);
}
public Iterator<T> iterator() {
return new BagIterator();
}
public class BagIterator<T> implements Iterator<T> {
private int index;
private String str;
public BagIterator() {
index = 0;
}
#Override
public boolean hasNext() {
return index < data.size();
}
#Override
public T next() {
str = (String) data.get(index);
if (str.startsWith("a"))
return (T) data.get(index++);
index++;
return null;
}
}
}
You can implement your own Iterator. Your iterator could be constructed to wrap the Iterator returned by the List, or you could keep a cursor and use the List's get(int index) method. You just have to add logic to your Iterator's next method AND the hasNext method to take into account your filtering criteria. You will also have to decide if your iterator will support the remove operation.
Here is the complete answer to the question.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
class ListIterator implements Iterator<String>{
List<String> list;
int pos = 0;
public ListIterator(List<String> list) {
this.list = list;
}
#Override
public boolean hasNext() {
while(pos < list.size()){
if (list.get(pos).startsWith("a"))
return true;
pos++;
}
return false;
}
#Override
public String next() {
if (hasNext())
return list.get(pos++);
throw new NoSuchElementException();
}
}
public class IteratorTest {
public static void main(String[] args) {
List<String> list = Arrays.asList("alice", "bob", "abigail", "charlie");
ListIterator itr = new ListIterator(list);
while(itr.hasNext())
System.out.println(itr.next()); // prints alice, abigail
}
}
ListIterator is the iterator for the array which returns the elements that start with 'a'.
There is no need for implementing an Iterable interface. But that is a possibility.
There is no need to implement this generically.
It fully satisfies the contract for hasNext() and next(). ie if hasNext() says there are still elements, next() will return those elements. And if hasNext() says no more elements, it returns a valid NoSuchElementException exception.