Passing object in Dlist. - java

The line "if (l.head.item != 9" gave me the error it said something like object is not compatible with int. I am really confused on why is that? How to fix it?
/DListNode1/
/* DListNode1.java */
public class DListNode1 {
public Object item;
// public short[][] colorVal;
public DListNode1 prev;
public DListNode1 next;
DListNode1() {
item = 0;
prev = null;
next = null;
}
DListNode1(Object i) {
item = i;
prev = null;
next = null;
}
}
//////////////
/* Double linked list */
public class DList1 {
protected DListNode1 head;
protected DListNode1 tail;
protected long size;
public DList1() {
head = null;
tail = null;
size = 0;
}
public DList1(Object a) {
head = new DListNode1();
tail = head;
head.item = a;
size = 1;
}
public DList1(Object a, Object b) {
head = new DListNode1();
head.item = a;
tail = new DListNode1();
tail.item = b;
head.next = tail;
tail.prev = head;
size = 2;
}
public void insertFront(Object i) {
DListNode1 temp = new DListNode1(i);
if (size == 0) {
head = temp;
tail = temp;
}
else {
temp.next = head;
head.prev = temp;
head = temp;
} size++;
}
public void removeFront() {
if (size == 0) {
return;
}
else if (size == 1) {
head = null;
tail = null;
size--;
}
else {
head = head.next;
head.prev = null;
size--;
}
}
public String toString() {
String result = "[ ";
DListNode1 current = head;
while (current != null) {
result = result + current.item + " ";
current = current.next;
}
return result + "]";
}
/////////////
public static void main(String[] args) {
DList1 l = new DList1();
l.insertFront(9);
if (l.head.item != 9) {
System.out.println("head.item is wrong.");

As others have pointed out, the problem is that the type of l.head.item is Object, and you can't compare that with an int using != or ==.
Options:
Cast l.head.item to Integer or int:
// This could be done in one step if you wanted
int headValue = (int) l.head.item;
if (headValue != 9)
Or
// This could be done in one step if you wanted
Integer headValue = (Integer) l.head.item;
if (headValue != 9)
Or you could do it inline:
if ((int) l.head.item != 9)
Use equals instead, which will automatically box the int to an Integer.
if (!head.equals(9))
Make your type generic instead, so you'd have a DListNode1<Integer>, and you could then be certain that all node values were Integer references (or null), and the != check would automatically unbox the Integer to an int and work.
Personally I'd definitely make this generic, but my guess is that you're relatively new to Java, and might not want to start with generics just yet.
Note that there's a difference between using equals and performing the unboxing: if the value of l.head.item is a reference to a non-Integer object, the first approach will throw a ClassCastException and the second will just go into the body of the if statement (as a string is not equal to 9, for example). Which of those is preferable depends on what you're trying to achieve in your bigger program: if it's entirely reasonable for your list to contain non-integers, you should use the equals check; if it actually indicates a programming error, then an exception is preferable as it alerts you to the error more quickly and stops your program from proceeding with invalid assumptions.
In both cases if l.head.item is null, you'll get a NullPointerException. This could be "fixed" using:
if (!Integer.valueOf(9).equals(l.head.item))
... but again it depends on what you want your code to do if the value is null.

Because a DListNode1.item is an Object not an Integer. Try casting to a Integer and compare to an Integer (9)

Compare using equals method.'==' will compare the refrence.
if(l.head.item.equals(new Integer(9))==false)

It will give you error because int is primitive:
Incompatible operand types Object and int
Change your code to:
if (!l.head.item.equals(new Integer(9))) {
Hope this helps.

Related

How to create a linked list in java without importing linked lists

i am a CS student in college and i am having trouble with this project where i am supoosed to create a linked list using nodes without importing linked lists, as well as doing a some methods with the list. i am a beginner when it comes to coding, so assume i know nothing, because that is probably the case lol.
import java.io.*;
import java.lang.*;
public class List {
public int listCount = 0;
public char[] linkedList;
public List() throws FileNotFoundException {
}
public List(char[] array) throws FileNotFoundException {
if (array.length == 1) {
Node head = new Node(array[0]);
} else if (array.length > 1) {
Node head = new Node(array[0]);
Node traverse = head;
for (int i = 1; i < array.length; i++) {
while (traverse.nextNode != null) {
traverse = traverse.nextNode;
}
traverse.nextNode = new Node(array[i]);
listCount++;
}
}
}
public List(String w) throws FileNotFoundException {
char[] array2 = new char[w.length()];
for (int i = 0; i < w.length(); i++) {
array2[i] = w.charAt(i);
}
List str = new List(array2);
}
/* Find the character at a index
#param int index
return the character at the chosen index
*/
public char charAt(int index) throws IndexOutOfBoundsException {
char results = linkedList[0];
if (index < linkedList.length && index >= 0) {
results = linkedList[index];
}
return results;
}
public String concat(int index1, int index2) {
return null;
}
/* Determine if the list is empty
return whether the given conditions are true or false
*/
public boolean isEmpty() {
for (int i = 0; i < linkedList.length; i++) {
if (!linkedList.equals(null)) {
System.out.println("This list is not empty");
return false;
}
}
System.out.println("List is empty");
return true;
}
/* Determine the size of the list
return the size of the list
*/
public int size() {
return listCount;
}
/* Create a new String between 2 index's including the start and end index
#param beginIndex is the starting point of the new String
#endIndex is the ending point of new String
return the new String
*/
public String subString(int beginIndex, int endIndex) {
return null;
}
public void insert(Object x) throws IndexOutOfBoundsException {
if (listCount > 100 || listCount < 0) {
throw new IndexOutOfBoundsException("Bag is too large");
} else {
this.linkedList[listCount] = (char) x;
listCount++;
}
}
}
i appreciate any help or pointers ahead of time. we are using a separate node, helper, and driver class as well as a .txt file to assign into my list. i am stuck on the concat and substring methods too, but i want to make sure i am getting the framework correct first. thank you again.
If i understand your question correctly, you are asking how to access a specific type without importing it.
Imports are required to identify which type is referenced when it is used by its simple name. To reference a type without declaring it in the imports you need to use its fully qualified name. For instance
java.util.List<String> someList = new java.util.ArrayList<>();
works without importing List and ArrayList because by declaring the package the class is in it is clear which class is being referenced.
I'll try to do the code later, but here is a book that i found that may help you.
https://cin.ufpe.br/~grm/downloads/Data_Structures_and_Algorithms_in_Java.pdf
I bought a book about DATA STRUCTURE from Pearson company, and it's really a good book, but i don't remember much, it's something like this, that i did in a hurry:
public class List {
private Node head = null;
private Node foot = null;
private Node newNode = null;
private Node auxNode = null;
public List() {
this.head = new Node();
this.foot = new Node();
}
public class Node {
private int adress;
private Node nextNode;
}
public void add(int value) {
this.newNode = new Node();
newNode.adress = value;
if (head == null) {
// Head of the list receive the values of the NEW NODE, so the head of the list
// is not null enymore
head = newNode;
head.nextNode = null;
} else {
// In this case Head is not null
/*The auxiliary node will receive the head and the new Node will become the new Head from the list*/
auxNode = new Node();
auxNode = head;
/*
while(auxNode.nextNode != null ) {
}
auxNode = head;
//head of the list is empty, so we can add the new node
head = newNode;//Here the new node is empty because was transfered to the head
head.nextNode = auxNode; //The head of the list receive the old node that used to be the head
if (head.nextNode == null) {
head.nextNode = newNode;
} else if (head.nextNode != null) {
}*/
}
}
}
```
I hope this help you to get some lead

Doubly Linked Lisl keeps getting null pointer error

I looked at all of the previous examples and cant see anything that I am doing wrong. I really struggle with null pointer exceptions for some reason and I just cant wrap my head around them.
public class DLBDictionary implements DictionaryInterface {
//Store Strings in an Node
public DLBNode firstNode;
public class DLBNode
{
public char value;
public DLBNode nextValue;
public DLBNode nextLetter;
public DLBNode(){
this.value = '/';
this.nextValue = null;
this.nextLetter = null;
}
public DLBNode(char value){
this.value = value;
this.nextValue = null;
this.nextLetter = null;
}
}
public DLBDictionary() {
DLBNode firstNode = new DLBNode('/');
}
// Add new String to end of list. If String should come before
// previous last string (i.e. it is out of order) sort the list.
// We are keeping the data sorted in this implementation of
// DictionaryInterface to make searches a bit faster.
public boolean add(String s) {
int charIndex = 0;
while(charIndex<=s.length())
{
char currentChar = s.charAt(charIndex);
boolean added = false;
while(!added)
{
if(firstNode.value == '/')
{
firstNode.value = currentChar;
added = true;
}
else if(firstNode.value == currentChar)
{
if(firstNode.nextLetter == null)
{
DLBNode newNode = new DLBNode();
firstNode.nextLetter = newNode;
firstNode = firstNode.nextLetter;
}
else
{
firstNode = firstNode.nextLetter;
}
added = true;
}
else
{
firstNode = firstNode.nextValue;
}
}
charIndex++;
}
DLBNode tempNode = new DLBNode('^');
firstNode.nextLetter = tempNode;
return true;
}
I left off the rest of my code but that last if statement is where I get the exception. It makes no sense to me! Didn't I initialize firstNode's value to '/' in the constructor? So firstNode.getValue should return '/' not a null pointer exception.
You should do
this.firstNode = new DLBNode();
in the constructor of DLBDictionary. You are actually creating a new object rather initializing your firstNode. Hope it helps.
You reset firstNode with several statements in the loop:
firstNode = firstNode.nextValue;
So it will happen that firstNode == null and this causes the NPE. The char value has nothing to do with it, it will be initialised to a character with value 0x00 anyway.

Null Pointers in my Queue (Link Lists)

Okay, I have this program almost done, but I'm lost at this point. I'm returning null pointers (it says on line 44 but that's just a while loop) and I need help fixing it please. I use a linked list to implement my queue, and my other two classes pass 100%, so the final class (CarQueue) is where the problem lies that is creating a Null Pointer.
public class CarQueue<E> {
private LinkNode<E> head;
private LinkNode<E> tail;
public CarQueue() {
head = null;
tail = null;
}
public CarQueue(E newData) {
LinkNode<E> temp = new LinkNode<E>(newData, null);
head = temp;
tail = temp;
}
public void addToQueue(E newData) {
LinkNode<E> temp = new LinkNode<E>(newData, null);
if (empty() == false) {
tail.setNext(temp);
tail = temp;
} else {
head = temp;
tail.setNext(temp);
tail = temp;
}
}
public String toString() {
LinkNode<E> temp = head;
String cars = "";
while (temp.getNext() != null) {
cars += temp.toString() + '\n';
}
return cars;
}
public E removeFmQueue() {
LinkNode<E> headReturn = head;
head = head.getNext();
return headReturn.getData();
}
public LinkNode<E> peek() {
return head.getNext();
}
public boolean empty() {
if (head == null)
return true;
else
return false;
}
}
If
while (temp.getNext() != null) {
is the line throwing an exception, then temp is null, (or, if it's even possible, getNext() is throwing a NullPointerException). But let's assume temp is the problem.
temp is being assigned to head, so is head being assigned to null?
If the zero-parameter constructor is called, but no other functions are called before calling toString(), then this would indeed result in temp being assigned null. Therefore, when you attempt temp.getNext(), a NullPointerException is thrown.
To prevent this, you could have an alternative value returned by the toString() method:
public String toString() {
if(head == null) {
return "no head. I got nothing.";
}
//print the other stuff...
}
But, really, the best solution is to never allow head--and therefore temp--to be null, as this means your class is in an unstable and basically-unusable state.
The most obvious way to prevent this is to eliminate the zero-parameter constructor--or alternatively have it only call the other constructor with a non-null value--and ensure that the other constructor never lets head remain as null.

Passing an Object into Dlist

/* DListNode1.java */
public class DListNode1 {
public Object item;
// public short[][] colorVal;
public DListNode1 prev;
public DListNode1 next;
DListNode1() {
item = 0;
prev = null;
next = null;
}
DListNode1(Object i) {
item = i;
prev = null;
next = null;
}
}
/* Double linked list */
public class DList1 {
protected DListNode1 head;
protected DListNode1 tail;
protected long size;
public DList1() {
head = null;
tail = null;
size = 0;
}
public DList1(Object a) {
head = new DListNode1();
tail = head;
head.item = a;
size = 1;
}
public DList1(Object a, Object b) {
head = new DListNode1();
head.item = a;
tail = new DListNode1();
tail.item = b;
head.next = tail;
tail.prev = head;
size = 2;
}
public void insertFront(Object i) {
DListNode1 temp = new DListNode1(i);
if (size == 0) {
head = temp;
tail = temp;
}
else {
temp.next = head;
head.prev = temp;
head = temp;
} size++;
}
public void removeFront() {
if (size == 0) {
return;
}
else if (size == 1) {
head = null;
tail = null;
size--;
}
else {
head = head.next;
head.prev = null;
size--;
}
}
public String toString() {
String result = "[ ";
DListNode1 current = head;
while (current != null) {
result = result + current.item + " ";
current = current.next;
}
return result + "]";
}
public class num{
public int j;
public num() {
this.j = 34;
}
}
public class testing{
private DList1 dli;
private num n;
public testing(){
dli = new DList1();
n = new num();
dli.insertFront(n);}
public static void main(String[] args) {
testing Jimmy = new testing();
System.out.printf(" this should be 34 %d\n",Jimmy.dli.head.item.j);// dont' work.
}
}
Can anyone tell me why I can't do Jimmy.dli.head.item.j? It makes perfect sense and yet, it said "j cannot be resolved or is not a field". How to fix it so that it will print 34? without this line "dli.insertFront(n.j);"
item is num right? isn't n.j = 34
Yes, you have created a num object and assigned it to item. However, item is a reference to the Object part of num only - hence, through this reference, you can only access those members which are part of the Object superclass (num implicitly inherits from Object).
IS there a way to access 34?
Yes, you can cast Jimmy.dli.head.item back to num to access the j member, like ((num)Jimmy.dli.head.item).j.
However, the proper way to implement this is to make DListNode1 and DList1 generic instead of using Object as the item element:
public class DListNode1 <T> {
public T item;
...
public class DList1 <T> {
protected DListNode1<T> head;
protected DListNode1<T> tail;
...
Wherever you are using Object in your DListNode1 and DList1 classes, use T now.
Then, you can instantiate a type safe DList1 like
DList1<num> dli = new DList1<>();
Since item is now of type num, and not Object, you can access its j element like you intended:
System.out.printf(" this should be 34 %d\n",Jimmy.dli.head.item.j);
See also The Java Tutorials, Lesson: Generics.
BTW, you should get used to the Code Conventions for the Java Programming Language - e.g. class names should start with a capital letter (Testing instead of testing, Num instead of num).

How do I add objects into a linked list?

I have been working on a project where I must implement a java class that implements the use of doubly linked lists. I have the LinkedList class finished with all my methods. I'm just unsure how to actually add node objects into the list. Here is my code so far with test at the bottom. Any help would be appreciated. Thanks
public class LinkedList {
private Node first;
private Node current;
private Node last;
private int currentIndex;
private int numElements;
public LinkedList() {
this.first = null;
this.last = null;
this.numElements = 0;
this.current = null;
this.currentIndex = -1;
}
private class Node {
Node next;
Node previous;
Object data;
}
public boolean hasNext() {
return (current != null && current.next != null);
}
public Object next() {
if (!this.hasNext()) {
throw new IllegalStateException("No next");
}
current = current.next;
return current.data;
}
public boolean hasPrevious() {
return (current != null && current.previous != null);
}
public Object previous() {
if (!this.hasPrevious()) {
throw new IllegalStateException("No previous");
}
current = current.previous;
return current.data;
}
int nextIndex() {
int index = numElements;
if (hasNext()) {
index = this.currentIndex + 1;
}
System.out.println(index + "The current index is " + current);
return index;
}
int previousIndex() {
int index = -1;
if (hasPrevious()) {
index = this.currentIndex - 1;
}
System.out.println(index + "The current index is " + current);
return index;
}
public void set(Object o) {
if (this.current == null) {
throw new IllegalStateException("No node found, cannot set.");
}
current.data = o;
}
public int size() {
return numElements;
}
public void add(Object o) {
Node newNode = new Node();
newNode.data = o;
if (first == null) {
first = newNode;
last = newNode;
newNode.next = null;
} else if (first != null) {
if (current == null) {
newNode.previous = null;
newNode.next = first;
first.previous = newNode;
first = newNode;
} else if (current == last) {
newNode.previous = current;
newNode.next = null;
current.next = newNode;
last = newNode;
} else {
newNode.previous = current;
newNode.next = current.next;
current.next.previous = newNode;
current.next = newNode;
}
}
current = newNode;
numElements++;
currentIndex++;
}
public void remove() {
if (current != null) {
if (current == first && current == last) {
first = null;
last = null;
} else if (current == last) {
current.previous = null;
last = current.previous;
} else if (current == last) {
current.previous.next = null;
last = current.previous;
} else {
current.previous.next = current.next;
current.next.previous = current.previous;
}
current = current.next;
numElements--;
}
}
}
import java.util.Scanner;
public class LinkedListTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String name;
int index;
LinkedList<Object> listOne = new LinkedList<Object>();
listOne.add(object o);
}
}
The posted class LinkedList looks functional to me.
Make sure that your test code does not confuse this class and java.util.LinkedList, which Java provides for you (It's a part of the existing Collections framework).
For clarity, I would recommend renaming your class to something like MyLinkedList
The following code works and the output is "0","2":
public class MyLinkedListTest {
public static final void main(String[] args) {
MyLinkedList list = new MyLinkedList();
System.out.println("Number of items in the list: " + list.size());
String item1 = "foo";
String item2 = "bar";
list.add(item1);
list.add(item2);
System.out.println("Number of items in the list: " + list.size());
// and so on...
}
}
I'd be surprised if your code compiled, since your class isn't actually generic. Just initialize it as LinkedList listOne = new LinkedList(); (no angle brackets).
As to actually adding elements, you just need an instance of some Object to add; anything will do (assuming your internal code works properly). Try this down at the end there:
Object objectToAdd = "Strings are Objects";
listOne.add(objectToAdd);
objectToAdd = new File("C:\\foo.bar"); // Or use any other Objects!
listOne.add(objectToAdd);
Think of numbered list and look at the relations between the elements
Say I have the list:
A
B
C
What do I have to do to the relations get the list:
A
B
NewNode
C
The new next node of B is NewNode
The new previous node of C is NewNode. So an insert function would want to know the immediate previous node or the immediate next node and then adjust the relationships.
Your LinkedList doesn't have generic types so you can't declare it as
LinkedList<Object> listOne = new LinkedList<Object>();
but rather as
LinkedList listOne = new LinkedList();
And now to add elements just use your add method
listOne.add("something");
listOne.add(1);//int will be autoboxed to Integer objects
Also if you want to add data from keyboard you can use something like
String line="";
do{
System.out.println("type what you want to add to list:");
line = keyboard.nextLine();
listOne.add(line);
}while(!line.equals("exit"));
The line
LinkedList<Object> listOne = new LinkedList<Object>();
won't compile unless you change your class declaration to
class LinkedList<T>
or alternately you can just write
LinkedList listOne = new LinkedLis();
After that you should be able to add objects to your list. However, you'll need to create an Object to add to it, listOne.add(object o); won't do--at the very least you'll have to write listOne.add(new Object()). (Your code does not instantiate an Object, there is no Object that you already have called o, and besides, object o does not mean anything in Java and would not compile.
As people have mentioned your list is not generic. However as they advise you to get rid of the parameter, you can also just add <Object> or <E> to your linked list implementation and leave your initialization of the list as it is.
So in your linked list class you should do something like:
public class LinkedList<E>
This will make sure when you're using LinkedList<Object> listOne = new LinkedList<Object>();, E will be covnerted to Object
Let's improve your test a little bit so that it becomes apparent where your problems are (if any) I commented out the call to the current() method since you have not included one. (I would leave this alone as it may confuse you.) The general idea would be to add items to the linked list and walk forward and backward through it checking the items with each step.
public class LinkedListTest {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String name;
int index;
LinkedList listOne = new LinkedList();
//Initially we should be empty so we are positioned
// at both the beginning and end of the list
assert listOne.size() == 0 :"List should be empty";
assert listOne.hasPrevious()==false: "Should be at the beginning of the list";
assert listOne.hasNext()==false : "Should be at the end of the list";
Object firstNode = "I am the first node";
listOne.add(firstNode); //we've added something
//I left this commented out since you don't have a current() method.
// assert firstNode == listOne.current() : "Our current item should be what we just added";
assert listOne.hasPrevious()==false : "Should not have moved forward in our list yet";
assert listOne.hasNext()==true : "should have an item after our current";
assert listOne.size() == 1 : "Should only have one item in the list";
Object secondNode = "I am the second node";
listOne.add(secondNode);
assert listOne.size() == 2 : "Should only have two items in the list";
assert firstNode == listOne.next() : "1st call to next should return the 1st node";
assert listOne.hasPrevious()==true : "We should be positioned after the 1st node";
assert listOne.hasNext()==true : "We should be positioned before the 2nd node";
}
}

Categories