findFirst method in SinglyLinkedList - java

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;
}
}

Related

Javafx right click edit listView item and similar methods

I am building a JavaFX todo list and am not sure how to continue. The right click popup menu works fine but I am not sure how to edit/change the contents of the ListView other than just removing them.
LocalEvent e = a string somehow?
I am trying to do 4 total things in a right click popup menu in Javafx:
Done is to place a check mark next to and strikeout the item.
Nest is to create a nested list from a list item (no idea at all how).
Edit is to make the list item editable and save the chages.
Remove works :)
I have done this by adding the following to the fxml file:
<JFXListView fx:id="eventList" editable="true" layoutX="24.0" layoutY="106.0" prefHeight="354.0" prefWidth="939.0">
<contextMenu>
<ContextMenu>
<items>
<MenuItem fx:id="popUp" mnemonicParsing="false" onAction="#Done" text="Done" />
<MenuItem fx:id="popUp3" mnemonicParsing="false" onAction="#Remove" text="Remove" />
<MenuItem fx:id="popUp1" mnemonicParsing="false" onAction="#Nest" text="Nest" />
<MenuItem fx:id="popUp2" mnemonicParsing="false" onAction="#Edit" text="Edit" />
</items>
</ContextMenu>
</contextMenu></JFXListView>`
Here is my Controller.java file:
package application;
import java.net.URL;
import java.time.LocalDate;
import java.util.ResourceBundle;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextField;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.DatePicker;
import javafx.scene.control.MenuItem;
import javafx.scene.input.MouseEvent;
public class Controller implements Initializable{
#Override
public void initialize(URL url, ResourceBundle rb) {
datePicker.setValue(LocalDate.now());
eventList.setExpanded(true);
eventList.depthProperty().set(1);
}
#FXML
private MenuItem popUp;
#FXML
private JFXTextField textBox;
#FXML
private JFXListView<LocalEvent> eventList;
ObservableList<LocalEvent> list = FXCollections.observableArrayList();
#FXML
private JFXButton AddButton;
#FXML
private DatePicker datePicker;
#FXML
void Submit(ActionEvent event) {
list.add(new LocalEvent(datePicker.getValue(), textBox.getText()));
eventList.setItems(list);
datePicker.setValue(LocalDate.now());
textBox.setText("");
}
#FXML
public void onEnter(ActionEvent event){
list.add(new LocalEvent(datePicker.getValue(), textBox.getText()));
eventList.setItems(list);
datePicker.setValue(LocalDate.now());
textBox.setText("");
}
#FXML
void Done(ActionEvent event) {
int index = eventList.getSelectionModel().getSelectedIndex();
String str = list.get(index).toString();
str = "[✓] " + str;
LocalEvent e = null; // <- how to put a string in here?
list.set(index, e);
eventList.setItems(list);
//eventList.setItems(list.set(index, element));
}
#FXML
void Remove(ActionEvent event) {
// remove selected task
list.remove(eventList.getSelectionModel().getSelectedIndex());
}
#FXML
void Nest(ActionEvent event) {
System.out.println("How the hell do I do that? lol");
// check for nested level
// create a nested list item
}
#FXML
void Edit(ActionEvent e) {
System.out.println("Edit selection");
eventList.setEditable(true);
int index = eventList.getSelectionModel().getSelectedIndex();
eventList.scrollTo(index);
eventList.layout();
eventList.edit(index);
eventList.layout();
}
}
LocalEvent is a java class file as follows:
package application;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javafx.beans.InvalidationListener;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
public class LocalEvent implements ObservableList<LocalEvent> {
private String description;
private LocalDate date;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public LocalEvent(LocalDate date, String description) {
this.setDate(date);
this.setDescription(description);
}
#Override
public String toString() {
return "At " + this.getDate() + ": " + this.getDescription();
}
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean contains(Object o) {
// TODO Auto-generated method stub
return false;
}
#Override
public Iterator<LocalEvent> iterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public Object[] toArray() {
// TODO Auto-generated method stub
return null;
}
#Override
public <T> T[] toArray(T[] a) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean add(LocalEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean remove(Object o) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean containsAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean addAll(Collection<? extends LocalEvent> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean addAll(int index, Collection<? extends LocalEvent> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean removeAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean retainAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public void clear() {
// TODO Auto-generated method stub
}
#Override
public LocalEvent get(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public LocalEvent set(int index, LocalEvent element) {
// TODO Auto-generated method stub
return null;
}
#Override
public void add(int index, LocalEvent element) {
// TODO Auto-generated method stub
}
#Override
public LocalEvent remove(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public int indexOf(Object o) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int lastIndexOf(Object o) {
// TODO Auto-generated method stub
return 0;
}
#Override
public ListIterator<LocalEvent> listIterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public ListIterator<LocalEvent> listIterator(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<LocalEvent> subList(int fromIndex, int toIndex) {
// TODO Auto-generated method stub
return null;
}
#Override
public void addListener(InvalidationListener listener) {
// TODO Auto-generated method stub
}
#Override
public void removeListener(InvalidationListener listener) {
// TODO Auto-generated method stub
}
#Override
public void addListener(ListChangeListener<? super LocalEvent> listener) {
// TODO Auto-generated method stub
}
#Override
public void removeListener(ListChangeListener<? super LocalEvent> listener) {
// TODO Auto-generated method stub
}
#Override
public boolean addAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean setAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean setAll(Collection<? extends LocalEvent> col) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean removeAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean retainAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public void remove(int from, int to) {
// TODO Auto-generated method stub
}
}
Any help at all appreciated.
The first thing that stands out was mentioned in the comments: your LocalEvent shouldn't implements ObservableList, it's just a data holder. You probably will want it to also hold a boolean to see if it's completed:
public class LocalEvent {
private String description;
private LocalDate date;
private boolean completed = false;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public void setCompleted(boolean completed) {
this.completed= completed;
}
public LocalEvent(LocalDate date, String description) {
this.setDate(date);
this.setDescription(description);
}
#Override
public String toString() {
String base = "At " + this.getDate() + ": " + this.getDescription();
return completed ? "[✓] " + base : base;
}
}
I don't know what the jfoenix controls are, but I'll assume they are close enough to JavaFX standard controls. The ListView should be bound to the list of events:
ObservableList<LocalEvent> list = FXCollections.observableArrayList();
ListView<LocalEvent> eventList = new ListView<>(list);
(I would also rename the lists to something that makes more sense.)
Now any change to list will be reflected in eventList so you don't need to touch eventList. This allows your done method to look like:
#FXML
void done(ActionEvent event) {
int index = eventList.getSelectionModel().getSelectedIndex();
LocalEvent localEvent = list.get(index);
localEvent.setCompleted(true);
list.set(index, localEvent);
}
Note that we needed to reset the item in the list because it doesn't know that a field of the LocalEvent instance has changed. You can make it that the fields also report changes by using an extractor, see here and many other answers here about it.
Editing depends on the cell used by the ListView, I would suggest reading about it in the docs and other questions here. Note that you probably want to be able to edit the description and date separately and not the whole toString value, so you'll have to provide a mechanism for that like bringing back the DatePicker.
Nesting depends on what you want it to look like. You might need to define your own cell factory, but consider just adding an indentation, via "\t"s, which will make it looks nested. If you really need a nesting in the data model, then each LocalEvent will have to hold its own ObservableList<LocalEvent> nestedEvents.
Also, method names should start with a lowercase.

anonymous inner class interface

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.

binary tree implementation with infinite loops

I have fixed the issue with the infinite loops but it seems like now when I try to use the function find, it always returns a value null. Any ideas of what's happening? Also for some reason I'm getting a NullPointerException in my delete function. Please can you help me here guys?
package ui;
import java.time.LocalDate;
import bp.BinaryTree;
public class Main {
public static void main(String[] args) {
BinaryTree myTree = new BinaryTree();
myTree.insert(LocalDate.of(2014,12,01));
myTree.insert(LocalDate.of(2014,12,02));
myTree.insert(LocalDate.of(2014,12,03));
myTree.insert(LocalDate.of(2013,12,04));
myTree.insert(LocalDate.of(2012,12,04));
myTree.insert(LocalDate.of(2011,12,04));
myTree.insert(LocalDate.of(2010,12,04));
myTree.insert(LocalDate.of(2014,12,04));
myTree.insert(LocalDate.of(2014,12,05));
myTree.insert(LocalDate.of(2014,12,06));
myTree.insert(LocalDate.of(2014,12,07));
System.out.println(myTree);
System.out.println(myTree.getSize());
System.out.println(myTree.showMaximumValue());
System.out.println(myTree.showMinimumValue());
System.out.println(myTree.find(LocalDate.of(2014,12,07)));
}
public class BinaryTree implements IBinaryTree {
public Node root = null;
private int sizeOfTree = 0;
#Override
public LocalDate showMinimumValue() {
Node current;
Node last=null;
current = root;
while (current != null) {
last = current;
current = current.getLeftChild();
}
return last.getDate();
}
#Override
public LocalDate showMaximumValue() {
Node current;
Node last=null;
current = root;
while (current != null) {
last = current;
current = current.getRightChild();
}
return last.getDate();
}
#Override
public boolean isEmpty() {
if (root == null) {
return true;
} else
return false;
}
public int getDepth(Node n) {
int currentDepth = 0;
int depth = 0;
if (n != null) {
currentDepth++;
if (currentDepth > depth) {
depth = currentDepth;
}
getDepth(n.getLeftChild());
getDepth(n.getRightChild());
currentDepth--;
}
return depth;
}
#Override
public int getSize() {
return sizeOfTree;
}
#Override
public void clear() {
root = null;
}
#Override
public void insert(LocalDate valueToInsert) {
if (isEmpty()) {
root = new Node(valueToInsert);
sizeOfTree++;
} else {
Node n = root;
Node oldParent = null;
boolean lastDirectWasLeft = false;
sizeOfTree++;
while (n != null) {
oldParent = n;
if (valueToInsert.isBefore(n.getDate())) {
n = n.getLeftChild();
lastDirectWasLeft = true;
} else {
n = n.getRightChild();
lastDirectWasLeft = false;
}
}
if (lastDirectWasLeft) {
oldParent.setLeftChild(new Node(valueToInsert));
} else {
oldParent.setRightChild(new Node(valueToInsert));
}
}
}
#Override
public void delete(LocalDate valueToDelete) {
Node current = root;
Node parent = root;
boolean isLeftChild = true;
while (current.getDate() != valueToDelete) {
parent = current;
if (valueToDelete.isBefore(current.getDate())) {
isLeftChild = true;
current = current.getLeftChild();
} else {
isLeftChild= false;
current = current.getRightChild();
}
if (current == null) {
break;
}
}
//When there is no children, cut the string
if(current.getLeftChild().equals(null)
&& current.getRightChild().equals(null)) {
if (current == root) {
root = null;
} else if (isLeftChild) {
parent.setLeftChild(null);
} else {
parent.setRightChild(null);
}
}
//When there is no right child, replace with left child
else if (current.getRightChild().equals(null)) {
if (current == root) {
root = current.getLeftChild();
} else if (isLeftChild) {
parent.setLeftChild(current.getLeftChild());
} else
parent.setRightChild(current.getLeftChild());
}
//When there is no left child, replace with right child
else if (current.getLeftChild() == null) {
if (current == root) {
root = current.getRightChild();
} else if (isLeftChild) {
parent.setLeftChild(current.getRightChild());
} else
parent.setRightChild(current.getRightChild());
}
//has grandchildren, pass them to the grandpas
else {
//find the grandchildren
Node successor = getSuccessor(current);
if (current == root) {
root = successor;
} else if (isLeftChild) {
parent.setLeftChild(successor);
} else {
parent.setRightChild(successor);
}
//bring grandkids and granppas together
successor.setLeftChild(current.getLeftChild());
}
}
private Node getSuccessor (Node otroNode) {
Node successorParent = otroNode;
Node successor = otroNode;
Node current = otroNode.getRightChild();
while (current != null) {
successorParent = successor;
successor = current;
current = current.getLeftChild();
}
if (successor != otroNode.getRightChild()) {
successorParent.setLeftChild(successor.getRightChild());
successor.setRightChild(otroNode.getRightChild());
}
return successor;
}
#Override
public Node find(LocalDate valueToFind) {
Node current = root;
while (current.getDate() != valueToFind) {
if (valueToFind.isBefore(current.getDate())) {
current = current.getLeftChild();
} else {
current = current.getRightChild();
}
if (current == null) {
return null;
}
}
return current;
}
if (isEmpty()) {
return null;
}
if (root.getDate().isAfter(valueToFind)) {
find(root.getLeftChild().getDate());
} else if (root.getDate().isBefore(valueToFind)) {
find(root.getRightChild().getDate());
} else if (root.getDate().equals(valueToFind) ) {
return root;
}
return null;
**/
private String toString(Node todoElArbol) {
if (todoElArbol == null){
return "";
} else {
return (toString(todoElArbol.getLeftChild()) + ","
+ todoElArbol.getDate() + ","
+ toString(todoElArbol.getRightChild()))
.replaceAll(",+", ",").replaceAll("^,", "").replaceAll(",$", "");
}
}
#Override
public String toString() {
return toString(root);
}
}
The Node class:
import java.time.LocalDate;
public class Node implements IBinaryTreeNode {
private LocalDate date;
private Node leftChild;
private Node rightChild;
public Node (LocalDate valueToInsert) {
date = valueToInsert;
}
#Override
public LocalDate getDate() {
return date;
}
#Override
public void setDate(LocalDate pDate) {
date = pDate;
}
#Override
public Node getLeftChild() {
return leftChild;
}
#Override
public void setLeftChild(Node pLeftChild) {
leftChild = pLeftChild;
}
#Override
public Node getRightChild() {
return rightChild;
}
#Override
public void setRightChild(Node pRightChild) {
rightChild = pRightChild;
}
}
Your binary search is.... broken.
#Override
public Node find(LocalDate valueToFind) {
if (isEmpty()) {
return null;
}
if (root.getDate().isAfter(valueToFind)) {
find(root.getLeftChild().getDate());
} else if (root.getDate().isBefore(valueToFind)) {
find(root.getRightChild().getDate());
} else if (root.getDate() == valueToFind) {
return root;
}
return null;
}
That method is supposed to recursively find a value in the tree (a depth-first search).
Methods like that are normally implemented in two parts, the public part, and the implementation for the recursion:
#Override
public Node find(LocalDate valueToFind) {
if (isEmpty()) {
return null;
}
return findRecursive(root, valueToFind);
}
then the private/recursive method:
private Node findRecursive(Node node, LocalDate valueToFind) {
if (node == null) {
return null;
}
if (node.getDate().isAfter(valueToFind)) {
return findRecursive(node.getLeftChild(), valueToFind);
}
if (node.getDate().isBefore(valueToFind)) {
return findRecursive(root.getRightChild(), valueToFind);
}
if (node.getDate().equals(valueToFind)) {
return node;
}
return null;
}
Note, no references to root in the recursive call, and also changed the == comparison to .equals(...).
I suggest the class Node should implement the Comparable interface, then you can get rid of the help method isBefore and isAfter, which will make your code much more readable.

Implement methods of an implemented List to an ArrayList

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

Getting null value

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.

Categories

Resources