I have this LinkedListDouble class which has the public ListIterator<T>listIterator() method,and I'm trying to execute the interface ListIterator as it's anonymous inner class,am I going the right path?what should I do to make the public int nextIndex()/public int previousIndex() work?
nextIndex method returns the index of the element that would be returned by a subsequent call to next, or list size if the list iterator is at the end of the list and the previousIndex method returns the index of the element that would be returned by a subsequent call to previous, or -1 if the list iterator is at the beginning of the list as it said here
here is the LinkedListDouble class
public class LinkedListDouble <T> {
private Node first = null;
private Node last = null;
public LinkedListDouble () // constructor
{
first = null; // no items on list yet
last = null;
}
public void add(T item) {
Node newNode = new Node(item);
if (isEmpty()) {
first =newNode;
last = newNode;
}
else {
//first.setPrev(newNode);
//newNode.setNext(first);
//first = newNode;
last.setNext(newNode);
newNode.setPrev(last);
last=newNode;
}
}
public boolean contains(T item){
if(first==null)
return false;
else
{
Node newNode=first;
while(newNode!=null)
{
if(newNode.getInfo().equals(item))
return true;
else
newNode=newNode.getNext();
}
}
return false;
}
public T remove(T item)
{//get care of first and last nodes
//and if there is more than 1 matching
boolean check=contains(item);
if(check==true)
{
Node newNode=first;
while(newNode!=null)
{
if(newNode.getInfo().equals(item))
{
newNode.getPrev().setNext(newNode.getNext());
newNode.getNext().setPrev(newNode.getPrev());
return item;
}
else
newNode=newNode.getNext();
}
}
return null;
}
public int size()
{
int size=0;
if(first==null)
return size;
else
{
Node newNode=first;
while(newNode!=null)
{
size++;
newNode=newNode.getNext();
}
}
return size;
}
public String toString()
{
Node newNode=first;
String s="";
while(newNode!=null)
{
s+=newNode.getInfo()+" ,";
newNode=newNode.getNext();
}
return s;
}
public boolean isEmpty() {
return first == null;
}
and here is the method that should execute the interface ListIterator as it's anonymous inner class and what I tried to do so far:
public ListIterator<T>listIterator()
{
ListIterator<T>listIterator = new ListIterator<T>() {
private Node current = first;
private Node temp2 = null;
private int curindex = 0;
#Override
public void add(T e) {
// TODO Auto-generated method stub
throw new RuntimeException();
}
#Override
public boolean hasNext() {
// TODO Auto-generated method stub
boolean flag=true;
if(current.getNext()==null)
{
flag=false;
}
return flag;
}
#Override
public boolean hasPrevious() {
// TODO Auto-generated method stub
boolean flag=true;
if(current.getPrev()==null)
{
flag=false;
}
return flag;
}
#Override
public T next() {
// TODO Auto-generated method stub
if (!hasNext()) throw new NoSuchElementException();
temp2=current.getNext();
current=current.getNext();
return (T) temp2.getInfo();
}
#Override
public int nextIndex() {
// TODO Auto-generated method stub
int counter=0;
if(!hasNext()) return size();
return curindex;
}
#Override
public T previous() {
// TODO Auto-generated method stub
if (!hasPrevious()) throw new NoSuchElementException();
temp2 = current.getPrev();
temp2 = temp2.getPrev();
return (T) temp2.getInfo();
}
#Override
public int previousIndex() {
// TODO Auto-generated method stub
int counter=0;
if(!hasPrevious()) return -1;
return curindex-1;
}
#Override
public void remove() {
// TODO Auto-generated method stub
throw new RuntimeException();
}
#Override
public void set(T e) {
// TODO Auto-generated method stub
throw new RuntimeException();
}
};
return listIterator;
}
This is a code sample from listIterator() method of LinkedList:
public E next() {
//check for modification
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public E previous() {
//check for modification
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
As you can see, you need to keep an variable like index to keep the track of next index.
The next index is incremented/decremented inside next() and previous() method and these methods already handles List size issue, hence no need to worry about size issue in nextIndex() and previousIndex() method.
Related
I'm trying to override a method that adds a string to a list. But i want the method to not add the string if the string is a duplicate in the list. If it isn't a duplicate than add if not do nothing. Here is my code. I'm just confused why it is not working.
public class Hw6 <T extends Comparable<? super T>> implements SortedListInterface<T>
{
private ListInterface<T> list;
public Hw6()
{
list = new LList<T>();
}
#Override
public boolean add(T newEntry) {
boolean results = false;
if(!contains(newEntry))
{
list.add(newEntry);
results = true;
}
return results;
}
public boolean addPrivate(T newEntry)
{
int newPosition = Math.abs(getPosition(newEntry));
return list.add(newPosition, newEntry);
}
#Override
public boolean remove(T anEntry) {
boolean result = false;
int position = getPosition(anEntry);
if (position > 0)
{
list.remove(position);
result = true;
}
return result;
}
#Override
public int getPosition(T anEntry) {
int position = 1;
int length = list.getLength();
while((position <= length) && (anEntry.compareTo(list.getEntry(position)) > 0))
{
position++;
}
if ((position > length) || (anEntry.compareTo(list.getEntry(position)) != 0))
{
position = -position;
}
return position;
}
#Override
public T getEntry(int givenPosition) {
return list.getEntry(givenPosition);
}
#Override
public boolean contains(T anEntry) {
boolean found = false;
for (int index = 0; !found && (index < getLength()); index++)
{
if (anEntry.equals(list.getEntry(index)))
found = true;
}
return found;
}
#Override
public int getLength() {
// TODO Auto-generated method stub
return list.getLength();
}
#Override
public boolean isEmpty() {
if(getLength() == 0)
return true;
else
return false;
}
#Override
public boolean isFull() {
return false;
}
public static void main(String args[])
{
LList<String> list = new LList<String>();
list.add("brad");
list.add("nick");
list.add("brad");
for(int i = 1; i <= list.getLength(); i++)
{
System.out.println(list.getEntry(i));
}
}
}
here is my output. i don't want it to add brad because its a duplicate
brad
nick
brad
It is because in your test you are creating a LList object but you should be creating a Hw6 object.
I have a simple ListModel, that is filterable and is used in a JList...
It uses the following code...
public class FilteredListModel extends AbstractListModel
{
private List<LineData> data = null;
private final ArrayList<Integer> indices = new ArrayList<Integer>();
public FilteredListModel()
{
}
public void setData(List<LineData> data)
{
this.data = data;
doFilter();
}
public void doFilter()
{
int oldSize = indices.size();
indices.clear();
if (data != null)
{
int count = data.size();
for (int i = 0; i < count; i++)
{
IFiltererListObject element = (IFiltererListObject) data.get(i);
if (element.isVisible())
indices.add(i);
}
}
fireContentsChanged(this, 0, getSize() - 1);
if (oldSize > getSize())
fireIntervalRemoved(this, getSize(), oldSize - 1);
}
#Override
public int getSize()
{
return indices.size();
}
#Override
public Object getElementAt(int index)
{
return data.get(indices.get(index));
}
#Override
public void addListDataListener(ListDataListener l)
{
// TODO Auto-generated method stub
//doFilter();
}
#Override
public void removeListDataListener(ListDataListener l)
{
// TODO Auto-generated method stub
//doFilter();
}
}
The strange thing about it is, that it is not working, just if I click for example outside the window, the JList with the ListModel get's correctly updated...
What am I missing here?
The problem is that the addListDataListener and removeListDataListener methods are empty. This means the JList can no longer attach its listener to the model. The call fireContentsChanged will do nothing, as the super class isn't aware of any listeners.
Either do not override those methods, or make sure you call super.addListDataListener as well.
#Robin please DYM???
import java.util.ArrayList;
import javax.swing.AbstractListModel;
import javax.swing.MutableComboBoxModel;
//usage == new JComboBox(new SectionComboBoxModel(new ArrayList());
public class SectionComboBoxModel extends AbstractListModel implements MutableComboBoxModel {
private static final long serialVersionUID = 1L;
private Object selectedItem;
private ArrayList<Object> sections;
public SectionComboBoxModel(ArrayList<Object> arrayList) {
sections = arrayList;
}
#Override
public Object getSelectedItem() {
return selectedItem;
}
#Override
public void setSelectedItem(Object newValue) {
selectedItem = newValue;
}
#Override
public int getSize() {
return sections.size();
}
#Override
public Object getElementAt(int i) {
return sections.get(i);
}
public void setElementAt(Object newValue, int i) {
this.fireContentsChanged(newValue, i, i);
this.sections.set(i, newValue);
}
#Override
public void addElement(Object obj) {
sections.add(obj);
this.fireIntervalAdded(obj, this.getSize() - 1, this.getSize() - 1);
}
#Override
public void removeElement(Object obj) {
this.fireIntervalRemoved(obj, sections.indexOf(obj), sections.indexOf(obj));
sections.remove(obj);
}
#Override
public void insertElementAt(Object obj, int index) {
sections.add(index, obj);
this.fireIntervalAdded(obj, index, index);
}
#Override
public void removeElementAt(int index) {
this.fireIntervalRemoved(sections.get(index), index, index);
sections.remove(index);
}
public void print() {
System.out.println("\nPrinting List");
for (int i = 0; i < this.sections.size(); i++) {
System.out.println(this.sections.get(i));
}
}
public boolean contains(Object o) {
return sections.contains(o);
}
public Object[] toArray() {
return this.sections.toArray();
}
}
I just updated my code, if someone can help me...in my findFirst method I wanted to look for the first node that includes the element and if such a node is found it returns the node otherwise null...so far in my method I did finding a node but Im not sure how to find the first node...how I would be able to do that ? this is what I have so far..thanks...
public SLNode<E> findFirst(E element){
SLNode<E> cursor = head.getSuccessor();
while(cursor != null){
if(cursor.getElement() !=null && cursor.getElement().equals(element))
return cursor;
cursor = cursor.getSuccessor();
}
return null;
}
Below are my actual classes
public class SinglyLinkedList<E> {
private final SLNode<E> head;
private final SLNode<E> tail;
int length;
// creates an empty list
public SinglyLinkedList() {
head = new SLNode<E>();
tail = new SLNode<E>();
head.setSuccessor(tail);
length = 0;
}
// adds new node on beginning of the list
public void add(E element) {
SLNode<E> node = new SLNode<E>(element, null);
node.setSuccessor(head.getSuccessor());
head.setSuccessor(node);
}
//removes a first node on beginning of the list
public boolean remove(E element) {
SLNode<E> previous = head;
SLNode<E> current = head.getSuccessor();
while (current != tail) {
if (current.getElement().equals(element)) {
previous.setSuccessor(current.getSuccessor());
//successor is next
return true;
}
previous = current;
current = current.getSuccessor();
}
return false;
}
public SLNode<E> findFirst(E element){
/*Shown At the Top as part of the Question*/
}
// adds new node on beginning of the list
public void add(SLNode<E> node) {
node.setSuccessor(head.getSuccessor());
head.setSuccessor(node);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
SLNode<E> cursor = head.getSuccessor();
while (cursor != tail) {
sb.append(cursor.getElement()).append(" ");
cursor = cursor.getSuccessor();
}
sb.append("\n");
return sb.toString();
}
}
SLnode class
public class SLNode<E> {
private E element;
private SLNode<E> successor;
public SLNode() {
element = null;
successor = null;
}
public SLNode(E theElement, SLNode<E> theSuccessor) {
element = theElement;
successor = theSuccessor;
}
public E getElement() {
return element;
}
public void setElement(E newElement) {
element = newElement;
}
public SLNode<E> getSuccessor() {
return successor;
}
public void setSuccessor(SLNode<E> newSuccessor) {
successor = newSuccessor;
}
public Object getPrevious() {
// TODO Auto-generated method stub
return null;
}
public void setPrevious(Object object) {
// TODO Auto-generated method stub
}
public void setNext(Object object) {
// TODO Auto-generated method stub
}
public Object getNext111() {
// TODO Auto-generated method stub
return null;
}
public Object getNext() {
// TODO Auto-generated method stub
return null;
}
public Object getPrevious1() {
// TODO Auto-generated method stub
return null;
}
public void setPrevious1(Object object) {
// TODO Auto-generated method stub
}
public Object getNext1() {
// TODO Auto-generated method stub
return null;
}
public void setNext11(Object object) {
// TODO Auto-generated method stub
}
public void setNext1(Object object) {
// TODO Auto-generated method stub
}
public Object getNext11() {
// TODO Auto-generated method stub
return null;
}
}
I know what to do with my programming code, but I just don't know why we have to do it.
My ArrayList class implements a List<E> interface. This means I have to copy all methods in my List interface to my ArrayList class. This is to stop the error of my ArrayList class saying: "ArrayList is not abstract and does not override abstract method iterator(int)" error. Can someone explain that to me in more detail?
Also: When I used the auto correct in NetBeans it says statements after each method "throw new UnsupportedOperationException("Not supported yet.");". Why?
Here's my code:
public class ArrayList<E> implements List<E> {
private E[] elementData;
private int elementCount;
private int capacityIncrement;
private static final int INVALID_INDEX=-1;
private static final int DEFAULT_CAPACITY = 100;
public ArrayList() {
capacityIncrement = 0;
elementData = (E[]) new Object[DEFAULT_CAPACITY];
}
public ArrayList(int capacity) {
this.capacityIncrement = 0;
this.elementData = (E[]) new Object[capacity];
}
public ArrayList(int capacity, int increment) {
this.capacityIncrement = increment;
this.elementData = (E[]) new Object[capacity];
}
private static class ArrayListIterator<E> implements Iterator<E> {
private ArrayListIterator(ArrayList c) {
elementData = c;
}
public interface List<E> {
public int size();
public boolean isEmpty();
public void clear();
public boolean contains(E element);
public void add(E element);
public boolean remove(E element);
public E elementAt(int index);
public int indexOf(E element);
public void insertElementAt(E element, int index);
public void removeElementAt(int index);
public void setElementAt(E element, int index);
public void removeDuplicates();
public void trimToSize();
public Iterator<E> iterator();
public Iterator<E> iterator(int index);
public String toString();
}
Since you implement an interface, you must implement all of the methods it declares (unless your class is abstract). Have a look at the Java tutorial trail on inheritance.
An interface is a contract that states that certain functionality will be provided by any class that implements it. That's done by specifying each of the method signatures (but, generally, no method bodies - so there's no actual implementation logic). So, if you have a class that implements that interface, you have to provide implementations for each of the methods so that your class fulfills that contract.
You implement the interface List so you need to implement all method which are defined in this interface. The exception says you should add the method iterator() to ArrayList.
An interface is like a contract which you (your class) sign(s). You have to fulfill everything which is defined in the contract or in other words you need to implement every (abstract) method from the interface.
Edit: I cleaned up the code and now the only thing you have to do is to implement every method with a // TODO comment in it.
public class ArrayList<E> implements List<E> {
private Object[] elementData;
private int elementCount;
private int capacityIncrement;
private static final int INVALID_INDEX = -1;
private static final int DEFAULT_CAPACITY = 100;
public ArrayList() {
capacityIncrement = 0;
elementData = new Object[DEFAULT_CAPACITY];
}
public ArrayList(int capacity) {
this.capacityIncrement = 0;
this.elementData = new Object[capacity];
}
public ArrayList(int capacity, int increment) {
this.capacityIncrement = increment;
this.elementData = new Object[capacity];
}
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void clear() {
// TODO Auto-generated method stub
}
#Override
public boolean contains(E element) {
// TODO Auto-generated method stub
return false;
}
#Override
public void add(E element) {
// TODO Auto-generated method stub
}
#Override
public boolean remove(E element) {
// TODO Auto-generated method stub
return false;
}
#Override
public E elementAt(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public int indexOf(E element) {
// TODO Auto-generated method stub
return 0;
}
#Override
public void insertElementAt(E element, int index) {
// TODO Auto-generated method stub
}
#Override
public void removeElementAt(int index) {
// TODO Auto-generated method stub
}
#Override
public void setElementAt(E element, int index) {
// TODO Auto-generated method stub
}
#Override
public void removeDuplicates() {
// TODO Auto-generated method stub
}
#Override
public void trimToSize() {
// TODO Auto-generated method stub
}
#Override
public Iterator<E> iterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public Iterator<E> iterator(int index) {
// TODO Auto-generated method stub
return null;
}
protected class ArrayListIterator<T> implements Iterator<T> {
private ArrayList<T> list;
private ArrayListIterator(ArrayList<T> list) {
this.list = list;
}
#Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
#Override
public T next() {
// TODO Auto-generated method stub
return null;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
}
}
interface List<T> {
public int size();
public boolean isEmpty();
public void clear();
public boolean contains(T element);
public void add(T element);
public boolean remove(T element);
public T elementAt(int index);
public int indexOf(T element);
public void insertElementAt(T element, int index);
public void removeElementAt(int index);
public void setElementAt(T element, int index);
public void removeDuplicates();
public void trimToSize();
public Iterator<T> iterator();
public Iterator<T> iterator(int index);
public String toString();
}
Since you are saying that your class "implements List", it must implement all methods defined in the List interface. An interface is like an abstract specification for your class, specifying what your class can do (its methods) without giving an details about what your class contains/how it does its work
I am using com.android.internal.telephony API's. In that I called two abstract classes they are Call.java and Connection.java. You can find these classes here http://hi-android.info/src/com/android/internal/telephony/Call.java.html and http://hi-android.info/src/com/android/internal/telephony/Connection.java.html for these created subclasses like
Call myCall = new MyCall();
Connection myConn = new MyConnection();
I need to use getDisconnectCause method from connection class which is an abstract method, I used like this:
myConn = myCall.getEarliestConnection();
if(myConn == null){
System.out.println("myConn is null ******");
}else
{
Connection.DisconnectCause cause = myConn.getDisconnectCause();
System.out.println("value of cause ******"+cause);
}
The subclass of Call.java is:
1. CallManager cm = CallManager.getInstance();
2. Phone.State state;
3.
4. public List<Connection> getConnections() {
5. state = cm.getState();
6. ringingCall = cm.getForegroundCalls();
7. System.out.println("**inside getConnections="+state);
8. System.out.println("**inside getConnections="+ringingCall);
9. if ( ringingCall == null) {
10. System.out.println("**call is null***");
11. return emptyConnections;
12. }
13. else
14. {
15. System.out.println("**call is not null***");
16. return ((Call) ringingCall).getConnections();
17. }
18. #Override
19. public Phone getPhone() {
20. return null;
}
#Override
public void hangup() throws CallStateException {
}
#Override
public boolean isMultiparty() {
return false;
}
public Connection
getEarliestConnection() {
List l;
long time = Long.MAX_VALUE;
Connection c;
Connection earliest = null;
68. l = getConnections();
if (l == null) {
return null;
}else if ( l.size() == 0)
{
return null;
}
for (int i = 0, s = l.size() ; i < s ; i++) {
c = (Connection) l.get(i);
long t;
t = c.getCreateTime();
if (t < time) {
earliest = c;
time = t;
}
}
return earliest;
}
}
AND the Connection.java subclass is:
class MyConnection extends Connection{
#Override
public void cancelPostDial() {
// TODO Auto-generated method stub
}
#Override
public String getAddress() {
// TODO Auto-generated method stub
return null;
}
#Override
public Call getCall() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getConnectTime() {
// TODO Auto-generated method stub
return 0;
}
#Override
public long getCreateTime() {
// TODO Auto-generated method stub
return 0;
}
#Override
public DisconnectCause getDisconnectCause() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getDisconnectTime() {
// TODO Auto-generated method stub
return 0;
}
#Override
public long getDurationMillis() {
// TODO Auto-generated method stub
return 0;
}
#Override
public long getHoldDurationMillis() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getNumberPresentation() {
// TODO Auto-generated method stub
return 0;
}
#Override
public PostDialState getPostDialState() {
// TODO Auto-generated method stub
return null;
}
#Override
public String getRemainingPostDialString() {
// TODO Auto-generated method stub
return null;
}
#Override
public UUSInfo getUUSInfo() {
// TODO Auto-generated method stub
return null;
}
#Override
public void hangup() throws CallStateException {
// TODO Auto-generated method stub
}
#Override
public boolean isIncoming() {
// TODO Auto-generated method stub
return false;
}
#Override
public void proceedAfterWaitChar() {
// TODO Auto-generated method stub
}
#Override
public void proceedAfterWildChar(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void separate() throws CallStateException {
// TODO Auto-generated method stub
}
}
EDIT 2 : I have edited line number 1 to 17. Plz check this. I am getting java.lang.ClassCastException: java.util.Collections error on Line No: 16 and Line No:68. Can anybody help me to resolve this. And also I am getting only one state of call i.e IDLE always even though the call is not-null . I am getting inside else part. plz help me.
#Override
public List<Connection> getConnections() {
return null;
}
This method on your MyCall class returns null and in your code for MyCall.getEarliestConnection(); it returns null if getConnections() returns null.
Your implementation of the getConnections() method has it returning null.
As you can see from the code inside getEarliestConnection(), if getConnections() returns null, then getEarliestConnection() will also return null.
Here is the relevant code:
#Override
public List<Connection> getConnections() {
return null;
}
...
l = getConnections();
if (l == null) {
return null;
}
I don't know what this code is supposed to do, but it's clear why that is null at that point.
In "MyCall.getEarliestConnection()", it calls it's own "getConnections()" method, which just returns null.