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.
Related
I have a class MyList with the following methods :
public class MyList{
ArrayList<Object> list;
MyList(int a, int b)
{
list = new ArrayList<Object>();
for(;a<=b;a++)
list.add(a);
}
public void add(int index, Object o)
{
list.add(index, o);
}
public Object remove(int index) throws isEmptyException
{
if(isEmpty())
throw new isEmptyException();
else
return list.remove(index);
}
public boolean isEmpty()
{
return list.isEmpty();
}
Here's my Class Queue. I have to implement the following methods using only the above methods from MyList.
public class Queue extends MyList{
public void enqueue(Object o)
{
//adds a new Object to the queue
}
public Object dequeue()
{
//removes the next Object from the queue and returns it
}
public boolean empty()
{
//Checks if the queue is empty
}
I don't really know where to start here, since I don't know the size of the queue. Can someone give me a hint how to solve this? Is a recursive method useful here?
Thanks in advance!
Call the add or remove inside the enqueue and dequeue methods of the Queue class, maintain a pointer to first and last.
public class Queue extends MyList {
private int index;
private int firstIndex;
Queue(int a, int b)
{
super(a, b);
}
public void enqueue(Object o)
{
add(o);
index++;
}
public Object deueue() throws Exception {
if(firstIndex == index || isEmpty()) {
firstIndex =0; index =0;
throw new Exception("");
}
else
return list.remove(++firstIndex);
}
public boolean isEmpty()
{
return list.isEmpty();
}
}
I'm trying to learn the Iterator design pattern in Java. Below is a code sample of the implementation of the iterator pattern.
public class IteratorDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
NameRepository repo=new NameRepository();
for(Iterator iter=repo.getIterarter(); iter.hasNext();){
String name=(String) iter.next();
System.out.println("Name : "+name);
}
}
}
interface Container{
public Iterator getIterarter();
}
interface Iterator{
public boolean hasNext();
public Object next();
}
class NameRepository implements Container{
private String[] names={"A","B","C","D","E","F"};
#Override
public Iterator getIterarter() {
return new NameIterator();
}
private class NameIterator implements Iterator{
int index;
#Override
public boolean hasNext() {
return index < names.length;
}
#Override
public Object next() {
if(this.hasNext()){
return names[index++];
}
return null;
}
}
}
Here the output is A , B, C, D,E ,F. My question is how this for loop iterates to the next item ? As it seems there is no iterating value in the code, but still it prints out the whole array
See, index is increasing every time if index < names.length
**
#Override
public Object next() {
if(this.hasNext()){
return names[index++];
}
return null;
}
**
Here is my class:
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node (){}
public Node (int x)
{
data = x;
}
public int data()
{
return data;
}
public Node next()
{
return next;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
Here is my interface:
public interface Set {
public boolean isEmpty();
public void makeEmpty();
public boolean isMember(int x);
public void add(int x);
public void remove(int y);
public void union(Set other, Set result);
public void intersection (Set other, Set result);
public void difference (Set other, Set result);
#Override
public String toString();
#Override
public boolean equals(Object other);
public void setList(int i); //i added this to use it as an identifier for each
//list element in the set array
public String getListId(); //these two extra methods make life easier
}
I have a method like this (in the LinkedListSet class):
public void difference (Set other, Set result)
{
if (other.isEmpty())
{
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty())
{
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
differenceHelper(this.first, othr.first, res);
result = res;
}// the print statements were added for debugging
The problem is, in the above method I am unable to cast the Set Other into its linked list implementation. When I call this method in the main program, the parameter is actually of type linked list (so I don't get any errors obviously).
However, all the instance variables are null. The list is empty before and after I cast it (when it actually isn't empty). I know this is because the interface doesn't include any information about the Nodes, but is there anything I can do other than editing the interface to incorporate the Node?
I hope I've made this clear enough. Any help would be appreciated.
edit:
In the main program I created an array of Sets.
Set[] sets = new Set[7];
for (int i = 0; i< sets.length; i++) //initialize each element
{
sets[i] = new LinkedListSet();
}
each list has nodes with data values which are added on later on in the code...
then I call the difference method.
sets[0].difference(sets[1], sets[4])
sets[1].isEmpty returns true for some reason (even though it is not).
If I were to do something like:
System.out.println(sets[1].first.data()) I would have no problem whatsoever.
For some reason all the values become null when the parameters are passed to the difference method.
public boolean isEmpty()
{
return first == null;
}
I tested what you are trying to do with the following code and I see no problems:
import org.junit.Test;
public class RandomCastTest {
public interface Set {
boolean isEmpty();
void add(int x);
void difference(Set other, Set result);
#Override
String toString();
#Override
boolean equals(Object other);
}
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node() {
}
public Node(int x) {
data = x;
}
public int data() {
return data;
}
public Node next() {
return next;
}
public void next(Node node) {
next = node;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
#Override
public boolean isEmpty() {
return first == null;
}
#Override
public void add(int x) {
Node node = new Node(x);
if (first == null) {
first = node;
} else {
Node currentNode;
Node nextNode = first;
do {
currentNode = nextNode;
nextNode = currentNode.next();
} while (nextNode != null);
currentNode.next(node);
}
Size++;
}
#Override
public void difference(Set other, Set result) {
if (other.isEmpty()) {
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty()) {
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
result = res;
}
}
#Test
public void test() {
Set[] sets = new Set[7];
for (int i = 0; i < sets.length; i++) {
sets[i] = new LinkedListSet();
}
for (int i = 0; i < 5; i++) {
sets[1].add(i);
}
for (int i = 5; i < 10; i++) {
sets[0].add(i);
}
sets[0].difference(sets[1], sets[4]);
// ... find difference
}
}
To simplify I removed unimplemented methods from the interface. Also added the add method implementation. Please see if it works for you.
I have Book and BookList classes. BookList is something like this:
public class BookList
{
private final List<Book> bList = new ArrayList<Book>();
public int size() { return bList.size(); }
public boolean isEmpty() { ... }
public boolean contains(Book b) { ... }
public boolean add(Book b) { ... }
public boolean remove(Book b) { .. }
public void clear() { ... }
public Book get(int index) { ... }
}
In my main class I want to print titles of books with in a for each loop:
for(Book b : bList)
{
b.print();
}
Eclipse says:
Can only iterate over an array or an instance of java.lang.Iterable
How can I get this working?
You need to implement the Iterable interface, which means you need to implement the iterator() method. In your case, this might look something like this:
public class BookList implements Iterable<Book> {
private final List<Book> bList = new ArrayList<Book>();
#Override
public Iterator<Book> iterator() {
return bList.iterator();
}
...
}
Implement the Iterable interface. That means you need to implement a method that returns an Iterator object that will iterate over the elements of a BookList.
In this case, your iterator() method could just return the result of calling bList.iterator(). (That will cause for (Book b : somBookList) to iterate over the Book objects in the BookList.bList ... )
In other cases, you might need to write your own Iterator<T> implementation class, complete with T next(), boolean hasNext() and remove() methods. For instance, if you wanted to prevent external code from removing elements from the BookList via your iterator, you might implement it like this:
public class BookList implements Iterable<Book> {
private final List<Book> bList = new ArrayList<Book>();
//...
#Override
public Iterator<Book> iterator() {
return new Iterator<Book> () {
private final Iterator<Book> iter = bList.iterator();
#Override
public boolean hasNext() {
return iter.hasNext();
}
#Override
public Book next() {
return iter.next();
}
#Override
public void remove() {
throw new UnsupportedOperationException("no changes allowed");
}
};
}
}
Here we can see the simple implementation of LinkedList with iterator and foreach syntax
class LinkedList implements Iterable<LinkedList.Node>{
private Node node;
public void add(Object data){
if(!Optional.ofNullable(node).isPresent()){
node = new Node();
node.setData(data);
}else{
Node node = new Node();
node.setData(data);
Node lastNode = getLastNode(this.node);
lastNode.setNext(node);
}
}
private Node getLastNode(Node node){
if(node.getNext()==null){
return node;
}else{
return getLastNode(node.getNext());
}
}
class Node{
private Object data;
private Node next;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public Iterator<Node> iterator() {
return new NodeIterator();
}
class NodeIterator implements Iterator<Node>{
private Node current;
public boolean hasNext() {
if(current == null){
current = node;
return Optional.ofNullable(current).isPresent();
}else{
current = current.next;
return Optional.ofNullable(current).isPresent();
}
}
public Node next() {
return current;
}
}
}
public class LinkedListImpl {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add("data1");
linkedList.add("data2");
linkedList.add("data3");
for(LinkedList.Node node: linkedList){
System.out.println(node.getData());
}
}
}
To be more specific about how to "implement the Iterable interface":
public class BookList implements Iterable<Book>
{
private final List<Book> bList = new ArrayList<Book>();
...
#Override
public Iterator<Book> iterator()
{
return bList.iterator();
}
}
For making a class iteratable you need to implement Iterable Interface.
a) Declare the class as below
public class BookList implements Iterable<Book>
b) Override the iterator() Method
Read More.
Hope it will help you.
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()>;
}