This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
I have written a small piece of code to implement a linked list data structure. I have an internal class "Node" that has two fields Node and value. Constructor of Linked list accept int value parameter and assign that value to the Node object and add the Node object to the LinkedList object.
My question is which code of java.util.LinkedList makes the list object to be printed as a list of number but not the address of its object?
As When i print "list1", the output is [3,4].
When I print "list", the output is hashcode of the object address.
I didn't find the toString() in java.util.LinkedList class.
How can I make my code to print the content of LinkedList?
Below is the code:
class LinkedList {
Node first;
Node getNode(){
return new Node();
}
class Node{
Node next;
int value;
}
void add(int value){
Node n=this.getNode();
n.value=value;
n.next=null;
if (first==null){
first=n;
} else{
first.next=n;
}
}
}
public class LinkedListTest{
public static void main(String[] args) {
LinkedList list=new LinkedList();
java.util.LinkedList<Integer> list1=new java.util.LinkedList<>();
list1.add(3);
list1.add(4);
list.add(1);
list.add(2);
System.out.println(list);
System.out.println(list1);
}
}
Your class LinkedList (I suggest you rename it since it might be confused with java.util.LinkedList) needs to override the method Object::toString, which is called within printing out to a console.
I didn't find the toString() in java.util.LinkedList class.
A bit detective job - you have to click through the source codes of LinkedList<E> which extends AbstractSequentialList<E> which extends AbstractList<E> which finally extends AbstractCollection<E> (source code) class where is overridden Object::toString method responsible for the String-alike representation of all the element. There you can get inspired.
How can I make my code to print the content of LinkedList?
This way:
#Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
if (first != null) {
Node temp = first;
String sep = "";
while (temp != null) {
sb.append(sep).append(temp.value);
temp = temp.next;
sep = ", ";
}
}
return sb.append(']').toString();
}
You have to create your own toString method for example
class LinkedList {
//...
#Override
public String toString() {
StringBuilder text = new StringBuilder("[");
String del = "";
if (first != null) {
do {
text.append(del).append(first.value);
first = first.next;
del = ", ";
} while (first != null);
}
text.append(']');
return text.toString();
}
}
If you run your code again, the Outputs
[1, 2]
Related
I have a custom generic linked list class called SLL. For the purpose of my program SLL is going to hold Word objects. In my Word class I have implemented the comparable interface, and defined three comparators. When I go to compile I get an error when trying to sort the custom list, using Collections.sort(). I cannot for the life of me figure out why. I have included some code below. The error message states:
//There is no suitable method found for sort(SLL<Word>, java.util.Comparator<Word>)
private static SLL<Word> wordList = new SLL<Word>();
//methods to populate custom generic list
private void printDescending ()
{
Collections.sort(wordList, Word.frequencyComp1);
System.out.println("10 Most Frequent");
printer(false);
}
My class declaration for SLL and a couple methods are as follows:
public class SLL <T extends Comparable <T>>
{
private Node<T> head , tail;
private int currentSize;
public SLL ()
{
this.head = null;
this.tail = null;
this.currentSize = 0;
}
public void add (Node<T> entry)
{
if (head == null)
{
Node<T> temp = entry;
head = temp;
tail = temp;
currentSize++;
}
else
{
Node<T> temp = entry;
tail.setNext(temp);
tail = temp;
currentSize++;
}
}
Any and all help would be greatly appreciated, I am on the last phase of my program :(
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List)
According to this, your list(SLL) must have a List interface.
private static SLL<Word> wordList = new SLL<Word>();
As per your code SLL is class and wordList is class object with the reference of word class.
If you want use the sort method of Collection class the wordList object must be collection type object like below:
List<SLL<Word>> wordList = new ArrayList<SLL<Word>>();
I have a class called SparseMatrix. It contains an ArrayList of Nodes (also class). I am wondering of how to iterate through the Array and access a value in Node. I have tried the following:
//Assume that the member variables in SparseMatrix and Node are fully defined.
class SparseMatrix {
ArrayList filled_data_ = new ArrayList();
//Constructor, setter (both work)
// The problem is that I seem to not be allowed to use the operator[] on
// this type of array.
int get (int row, int column) {
for (int i = 0; i < filled_data_.size(); i++){
if (row * max_row + column == filled_data[i].getLocation()) {
return filled_data[i].getSize();
}
}
return defualt_value_;
}
}
I will probably switch to static arrays (and remake it every time I add an object). If anyone has a solution, I would very much appreciate you sharing it with me. Also, thank you in advance for helping me.
Feel free to ask questions if you don't understand anything here.
Assuming filled_data_ is a list that contains list of objects of a class named Node.
List<Nodes> filled_data_ = new ArrayList<>();
for (Node data : filled_data_) {
data.getVariable1();
data.getVariable2();
}
More info http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/
First of all, you should not use raw types. See this link for more info: What is a raw type and why shouldn't we use it?
The fix is to declare the type of object held by your array list. Change the declaration to:
ArrayList<Node> filled_data_ = new ArrayList<>();
Then you can access each element in the array list using filled_data_.get(i) (as opposed to filled_data_[i], which would work for a regular array).
`filled_data_.get(i)`
The above will return the element at index i. Documentation here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int)
If you didn't use generic, then you need to cast the object
//Assume that the member variables in SparseMatrix and Node are fully defined.
class SparseMatrix {
ArrayList filled_data_ = new ArrayList();
//Constructor, setter (both work)
// The problem is that I seem to not be allowed to use the operator[] on
// this type of array.
int get (int row, int column) {
for (int i = 0; i < filled_data_.size(); i++){
Node node = (Node)filled_data.get(i);
if (row * max_row + column == node.getLocation()) {
return node.getSize();
}
}
return defualt_value_;
}
}
If array list contains Nodes which defines getLocation() you could use :
((Nodes)filled_data_.get(i)).getLocation()
You could also define
ArrayList<Nodes> filled_data_ = new ArrayList<Nodes>();
When you create the ArrayList object, you should specify the type of the contained elements with <> brackets. It is also good to keep the reference to the List interface - not ArrayList class. To iterate through such a collection, use foreach loop:
Here is an example of the Node class:
public class Node {
private int value;
public Node(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Here is an example of the Main class:
public class Main {
public static void main(String[] args) {
List<Node> filledData = new ArrayList<Node>();
filledData.add(new Node(1));
filledData.add(new Node(2));
filledData.add(new Node(3));
for (Node n : filledData) {
System.out.println(n.getValue());
}
}
}
I have got a txt file (representing nodes and cost in the graph) which has the following format:
A B 2
A C 3
A D 4
B C 2 . . .
I have got a class called Node to represent the above data. Following is my Node class
class Node{
Node leftchild;
Node rightchild;
int cost;
public Node(Node firstchild, Node secondchild, int cost){
this.leftchild = firstchild;
this.rightchild = secondchild;
this.cost = cost;
}
public Node(Node firstchild, Node secondchild) {
this.leftchild = firstchild;
this.rightchild = secondchild;
}
public ArrayList<Node> getChildren(){
ArrayList<Node> childNodes = new ArrayList<Node>();
if(this.leftchild != null)
{
childNodes.add(leftchild);
}
if(this.rightchild != null)
{
childNodes.add(rightchild);
}
return childNodes;
}
public boolean removeChild(Node n){
return false;
}
}
I would now like to read the data (above mentioned format) from a file and store it in a three dimensional array like following
[A] [B] [2]
[A] [C] [3]
.. So on
I have got the following method to read the data from the file and storing it in an array, but I am getting an error while adding the tokens to the arraylist.
My error is saying as: Incompatible types: String cannot be converted to Node.
I am not sure how to fix this. Any kind of help is much appreciated. Thanks.
public Node[][][] getNodes(File file) throws IOException {
FileReader inputHeuristic = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
List list = new ArrayList();
while ((line = bufferReader.readLine()) != null) {
String[] tokens = line.split(" ");
list.add(new Node(tokens[0], tokens[1], tokens[2]));
}
bufferReader.close();
return list.toArray(new Node[list.size()]); // converting list to array
}
What you are trying to do does not make much sense. You cannot change something that is a type String to a class object. Either you need to change what is being passed to the constructor or you need to change the type of the instance variables to String.
Personally I would change the Node type variables to the String Type. You will also need to parse the token[2] so its an int. i.e Integer.parseInt(token[2]);
For my assignment we are to make an emulation of a LISP Linked List in Java. There are two types of List, an EmptyList and a NonEmptyList. The EmptyList is mostly trivial and only serves the purpose of ending the Linked List. The way it is supposed to work is that each List has a head and a tail. The head is an Object and the Tail is the next Linked List. I have a Linked List interface as follows:
public interface LispList {
EmptyList NIL = new EmptyList();
boolean empty();
Object head();
LispList tail();
LispList cons(Object inputHead);
}
And here is the NonEmptyList class:
public class NonEmptyList implements LispList{
Object head;
LispList tail;
public NonEmptyList(Object inputHead) {
this.head = inputHead;
this.tail = new NonEmptyList(head);
}
public boolean empty() {
return false;
}
public Object head() {
return head;
}
public LispList tail() {
return tail;
}
public String toString() {
return head() + " " + tail().toString();
}
public NonEmptyList cons(Object inputHead) {
NonEmptyList a = new NonEmptyList(inputHead);
return a;
}
public class NIL{
EmptyList NIL;
}
}
EmptyList:
public class EmptyList implements LispList {
public EmptyList() {
}
public boolean empty() {
return true;
}
public Object head() {
throw new UnsupportedOperationException("EmptyList");
}
public LispList tail() {
throw new UnsupportedOperationException("EmptyList");
}
public String toString() {
return "";
}
public class NIL{
EmptyList NIL;
}
public NonEmptyList cons(Object inputHead) {
NonEmptyList a = new NonEmptyList(inputHead);
return a;
}
}
And here is my tester:
public class LispListTest {
public static void main(String[] args) {
LispList list = LispList.NIL.cons("C").cons("B").cons("A");
System.out.println(list.tail());
System.out.println(list.toString());
}
}
The problem I am having is in the constructor of the NonEmptyList. The way I have it currently gives me a Stack Overflow Exception. I have tried a few different things and none of them work the way I need them to. I'm not sure how to make the constructor so the tail points to the next list.
This is my first attempt at a linked list so I might be making a pretty simple mistake.
Short anwser
First, EmptyList class needs to be singleton. Not sure how to achieve it Java, but you shouldn't open the constructor to everybody to use.
Then, the constructor for NonEmptyList should take two arguments:
The object for the head.
The tail, the instance of LispList. Better if you overload the constructor with this argument defaulting to EmptyList (singleton) instance.
Currently, in the constructor NonEmptyList you recursively call it when assigning the tail: in a way you are constructing an infinite list with repeated element: (a) this is not what you want and (b) without laziness this will cause stack overflow.
Lastly, cons is a constructor for a non-empty list, thus there is no need for a method called cons.
A guide into Lisp lists
Most Lisp dialects construct the list on the top of a pair. There is some criticism about the way Lisps do it: this introduces concepts of proper and improper lists and it's hard to define a generic comparison on lists. Yet, it's an easy and efficient way to do it.
A pair is constructed using CONS function (I will be using Common Lisp, CL, for demonstration):
(cons 12 45) => (12 . 45)
Notice the dot in the printed form of the pair. Parts of the pair can be extracted using functions CAR and CDR:
(car (cons 12 45)) => 12
(cdr (cons 12 45)) => 45
Pairs can be combined with other pairs:
(cons (cons (cons 1 2) 3) (cons 4 5))
=> (((1 . 2) . 3) 4 . 5)
CL provides combination functions of CAR and CDR to extract sub-pairs, e.g. CDDAR is a shortcut for (CDR (CDR (CAR OBJ))): it takes the first item of the pair (which must be a pair itself), then the second item of the result and the second item of that result.
Lisps also define a special object of an empty pair, or nothing (but in fact, this object is not a pair, it's like mathematical "empty set" which is not a set...). In CL there two synonyms for it: NIL or ().
A list is constructed using pairs ordered in certain way. A list is:
Either NIL, or empty
Or a (CONS OBJ TAIL), where OBJ is any object and TAIL is a list.
To distinguish operations on pairs and their combinations from operations on lists, Common Lisp provides synonymous functions:
FIRST extracts the first item of the list (aka head), synonym for CAR.
REST returns the tail of the list, synonym for (CAR (CDR LIST)) or (CADR LIST).
So, here are examples of lists:
NIL is an empty list
(CONS 1 NIL) (printed (1)) is the list of one element; FIRST will return 1 and REST will return an empty list NIL.
(CONS 1 (CONS 2 NIL)) (printed (1 2)) is the list of two elements; FIRST will return 1 and REST will return the tail list (2).
Generally, the list of numbers from 1 to N will be (CONS 1 (CONS 2 (CONS 3 ... (CONS N NIL) ..))).
Here is correct and tested answer:
LispList interface:
public interface LispList
{
LispList NIL = new EmptyList();
boolean isEmpty();
Object head();
LispList tail();
LispList cons(Object head);
}
EmptyList class
public class EmptyList implements LispList {
public String toString() {
return "";
}
#Override
public boolean isEmpty() {
return true;
}
#Override
public Object head() {
throw new UnsupportedOperationException();
}
#Override
public LispList tail() {
throw new UnsupportedOperationException();
}
#Override
public LispList cons(Object head) {
return new NonEmptyList(head, new EmptyList());
}
}
NonEmptyList class
public class NonEmptyList implements LispList {
private LispList tail;
private Object head;
public NonEmptyList(Object head, LispList tail) {
this.head = head;
this.tail = tail;
}
public String toString() {
return head() + " " + tail().toString();
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public Object head() {
return head;
}
#Override
public LispList tail() {
return tail;
}
#Override
public LispList cons(Object head) {
return new NonEmptyList(head, new NonEmptyList(head(), tail));
}
}
And test main class:
public class LispListTester
{
public static void main(String[] args)
{
LispList list1 = new EmptyList();
System.out.println("[" + list1 + "]");
System.out.println("Expected: []");
LispList list2 = new NonEmptyList("A", new EmptyList());
System.out.println(list2);
System.out.println("Expected: A");
LispList list3 = new NonEmptyList("A", new NonEmptyList("B",
new NonEmptyList("C", new EmptyList())));
System.out.println(list3);
System.out.println("Expected: A B C");
LispList list4 = LispList.NIL.cons("E").cons("D").cons("C").cons("B").cons("A");
System.out.println(list4);
System.out.println("Expected: A B C D E");
}
}
class Link {
public Link next;
public String data;
}
public class LinkedList {
public static void main(String[] args) {
String myArray[] = new String[2];
myArray[0] = "John";
myArray[1] = "Cooper";
Link first = null;
Link last = null;
while (myArray.hasNext()) {
String word = myArray.next();
Link e = new Link();
e.data = word;
//... Two cases must be handled differently
if (first == null) {
first = e;
} else {
//... When we already have elements, we need to link to it.
last.next = e;
}
last = e;
}
System.out.println("*** Print words in order of entry");
for (Link e = first; e != null; e = e.next) {
System.out.println(e.data);
}
}
}
LinkedList.java:16: cannot find symbol symbol : method hasNext()
location: class java.lang.String
while (myArray.hasNext()) {
^ LinkedList.java:17: cannot find symbol
symbol : method next() location: class java.lang.String
String word = myArray.next();
^ 2 errors
Few Questions...
Why did this error occur, i am trying to pass my Array of Strings. Still its not taking.
Can't we not declare Array of Strings like in JavaScript way.
String myArray[] = ["assa","asas"];
What does the hasNext() and the next Method do?
Java arrays don't have next and hasNext methods on them. You are probably thinking of iterators, which are typically used with container classes/interfaces such as java.util.List.
Note that you can initialize String arrays thus:
String[] myArray = { "foo", "bar" };
Here is a much more succinct way to iterate through the array
for(String word : myArray) {
//Keep the rest of the code the same(removing the String word = myArray.next(); line
}
That will iterate through the array, assigning the current value to word at each pass.