Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: ClassCastException in Double Linked List toString

  1. #1
    Junior Member
    Join Date
    Apr 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default ClassCastException in Double Linked List toString

    Hey , for my class I have to create an Infinite Integer class which holds can hold a really, really large integer using a doubly linked list. It holds 3 integers per node, so 5697343 would be held like
    [5] [697] [343]. And the toString would like like 5,697,343. Or ifs its 568007 the DLL would look like
    [568][7] and the toString would add "00" to the node data that is less than 10.
    My problem is the toString method-

    public String toString()
    		{
    			String commaString= "";
    			DLLNode node;
    			int num;
    			int realSize = data.size();
     
     
    			node = data.head;
    				for( int i = 0; i < realSize; i++)
    				{
    					if( i == 0)
    					{
     
    						commaString = commaString + node.toString();
     
    						System.out.println(commaString);
    					}
     
    					else
    					{
     
    						if((Integer)node.data < 10)
    						{
    							commaString = (commaString + ",00" + node.toString());
     
    							System.out.println(commaString);
    						}
     
    						else
    						{
     
    							commaString = (commaString + "," + node.toString());
     
    							System.out.println(commaString);
    						}
    					node = node.next;
    					}
    				}
     
    			return commaString;
    	}
    The problem occurs at this part
    if((Integer)node.data < 10)
    its not a compile time error but I get a ClassCastException

    Any help would be appreciated


  2. #2
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Need some help with Doubly Linked List toString

    Hey Rastabot,

    Could you please post the entire class for me to look at?
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  3. #3
    Junior Member
    Join Date
    Apr 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need some help with Doubly Linked List toString

    Yeah heres the whole class-
    import java.util.*;
     
     
    public class InfiniteInt <E> extends DLList  implements Comparable
    {
     
    	DLList data = new DLList();
     
    	public InfiniteInt(String str)
    	{
    		String mod1String;
    		String mod2String;
    		int size;
    		size = str.length();
     
    		if(size % 3 == 0)
    		{
    			for(int i = 0; i < size; i = i + 3)
    			{
     
    				int place = i + 3;
    				data.addLast(str.substring(i, place));
    			}
     
    		}
     
    		else if ( size % 3 == 2)
    		{
    			data.addLast(str.substring(0, 2));
    			mod2String = str.substring(2);
     
    			for(int i = 0; i< mod2String.length(); i = i + 3)
    			{
     
    				int place = i + 3;
    				data.addLast(mod2String.substring(i, place));
    			}
     
    		}
     
    		else if( size % 3 == 1)
    		{
    			data.addLast(str.substring(0,1));
    			mod1String = str.substring(1);
     
    			for(int i = 0; i < mod1String.length(); i = i + 3)
    			{
    				System.out.println(data.toString());
    				int place = i + 3;
    				data.addLast(mod1String.substring(i, place));
    			}
     
     
    		}
    	}
     
    	public InfiniteInt()
    	{
    		data.addFirst(0);
    	}
     
    public String toString()
    	{
    		String commaString= "";
    		DLLNode ptr;
    		int num;
    		int realSize = data.size();
     
     
    		ptr = data.head;
    			for( int i = 0; i < realSize; i++)
    			{
    				if( i == 0)
    				{
     
    					commaString = commaString + ptr.toString();
     
    					System.out.println(commaString);
    				}
     
    				else
    				{
     
    					if((Integer)ptr.data < 10)
    					{
    						commaString = (commaString + ",00" + ptr.toString());
     
    						System.out.println(commaString);
    					}
     
    					else
    					{
     
    						commaString = (commaString + "," + ptr.toString());
     
    						System.out.println(commaString);
    					}
    				ptr = ptr.next;
    				}
    			}
     
    		return commaString;
    	}
     
     
    	public static InfiniteInt add(InfiniteInt infInt1, InfiniteInt infInt2)
    	{
    		int	largerInfInt;
    		int carryValue = 0;
     
    		DLLNode ptr1 = infInt1.tail;
    		DLLNode ptr2 = infInt2.tail;
    		InfiniteInt int3 = new InfiniteInt("");
     
    		System.out.println(infInt1.size());
    		if(infInt1.size() > infInt2.size())
    				largerInfInt = infInt1.size();
    		else
    				largerInfInt = infInt2.size();
     
    		for(int i = 0; i < largerInfInt; i++)
    		{
    			Integer test = (Integer)ptr1.data + (Integer) ptr2.data;
     
    			if(carryValue == 1)
    				{
    					test = test + 1;
    					carryValue = 0;
    				}
     
    			if(test < 1000)
    				int3.addFirst(test.toString());
     
    			else
    			{
    				int carry = test - 1000;
    				carryValue = 1;
    				int3.addFirst(carry);
    			}
     
    			ptr1 = ptr1.prev;
    			ptr2 = ptr2.prev;
    		}
     
    		return int3;
    	}
     
    	public int compareTo(Object o)
    	{
     
     
    		System.out.println();
     
    		InfiniteInt passedInInt;
    		passedInInt = (InfiniteInt) o;
     
    		DLLNode ptr1 = data.head;
    		DLLNode ptr2 = passedInInt.head;
    		int compareInt = 0;
     
    		int breakInt = data.size();
     
    		System.out.println(" This is the size of the data: " + data.size() + " This is the size of the passed in Int: " + passedInInt.size());
    		if(data.size() > passedInInt.size())
    			compareInt = 1;
     
    		else if(data.size() < passedInInt.size())
    			compareInt = -1;
     
    		else
    		{
     
     
     
    			for(int i = 0; i < data.size(); i++)
    			{
     
    				if((Integer)ptr1.data > (Integer)ptr2.data)
    				{
    					compareInt = 1;
    					i = breakInt;
    				}
     
    				else if((Integer)ptr2.data > (Integer)ptr1.data)
    				{
    					compareInt = -1;
    					i = breakInt;
    				}
     
    				ptr1 = ptr1.next;
    				ptr2 = ptr2.next;
    			}
    		}
    		return compareInt;
    	}
     
    }
    Heres the DLList class you'll need-
    //This will implement a "doubly linked list" that is set up to hold whatever
    //the user defines it to hold at run time (using Generics)
     
    import java.util.*;
     
    public class DLList<E>
    {
    	//data
    	 DLLNode<E> head, tail;
     
    	//constructor
    	public DLList()
    	{
    		head = tail = null;
    	}
     
    	//methods
    	//-----------------------------------
    	//addLast - adds theElement to the end of the list in its own node
    	public void addLast(E theElement)
    	{
    		//create a node to hold it
    		DLLNode<E> newNode = new DLLNode<E>(theElement);
     
    		//if the list is empty, then it becomes the only node
    		if (head == null)
    			head = tail = newNode;
     
    		//otherwise, change the links so it is the last node
    		else
    		{
    			tail.next = newNode;
    			newNode.prev = tail;
    			tail = newNode;
    		}
    	}
     
    	//-----------------------------------
    	//addFirst - adds theElement to the front of the list in its own node
    	public void addFirst(E theElement)
    	{
    		//create a node to hold it
    		DLLNode<E> newNode = new DLLNode<E>(theElement);
     
    		//if the list is empty, then it becomes the only node
    		if (head == null)
    			head = tail = newNode;
     
    		//otherwise, change the links so it is the first node
    		else
    		{
    			newNode.next = head;
    			head.prev = newNode;
    			head = newNode;
    		}
    	}
     
    	//-----------------------------------
    	//toString - returns its representation as a String
    	public String toString()
    	{
    		String outString = "[";
    		DLLNode<E> ptr = head;
    		while (ptr != null)
    		{
    			if (ptr != head)    //only put in , if not the head
    				outString = outString + ", " + ptr;
    			else
    				outString = outString + " " + ptr;    //just a blank, then data pointed to by ptr
    			ptr = ptr.next;
    		}
    		outString = outString + " ]";
     
    		return outString;
    	}
     
    	//backwards - returns its backwards representation as a String by following the prev links
    	public String backwards()
    	{
    		String outString = "[";
    		DLLNode<E> ptr = tail;
    		while (ptr != null)
    		{
    			if (ptr != tail)    //only put in , if not the tail
    				outString = outString + ", " + ptr;
    			else
    				outString = outString + " " + ptr;    //just a blank, then data pointed to by ptr
    			ptr = ptr.prev;
    		}
    		outString = outString + " ]";
     
    		return outString;
    	}
     
    	//-----------------------------------
    	//size - traverses the list, counting how many elements there are.  Returns size
    	public int size()
    	{
    		int total = 0;
    		DLLNode<E> ptr = head;
    		while (ptr != null)   //walks through the linked list,
    		{
    			total++;				//counting up how many nodes there are
    			ptr = ptr.next;
    		}
    		return total;
    	}
     
    	//-----------------------------------
    	//isEmpty - returns if it is empty
    	public boolean isEmpty()
    	{
    		return head == null;
    	}
     
    	//-----------------------------------
    	//clear - "clears" the list by resetting head and tail to null
    	public void clear()
    	{
    		head = tail = null;
    	}
     
    	//-----------------------------------
    	//getFirst - returns the first element on the list without removing it
    	public E getFirst()
    	{
    		if (head == null)    //empty
    			throw new NoSuchElementException("the list is empty");
    		return head.data;
    	}
     
    	//-----------------------------------
    	//getLast - returns the last element on the list without removing it
    	public E getLast()
    	{
    		if (tail == null)    //empty
    			throw new NoSuchElementException("the list is empty");
    		return tail.data;
    	}
     
    	//-----------------------------------
    	//removeFirst - removes and returns the first element on the list
    	public E removeFirst()
    	{
    		//case 1: is it empty?
    		if (head == null)
    			throw new NoSuchElementException("the list is empty");
     
    		//case 2: if there is only 1 element on the list
    		else if (head == tail)    //already handled the case where they were both null
    		{
    			E dataToReturn = head.data;    //store the data that will be returned
    			head = tail = null;     //make the list empty
    			return dataToReturn;   //return the data
    		}
     
    		//case 3: if there are lots of elements on the list
    		else
    		{
    			E dataToReturn = head.data;    //store the data that will be returned
    			head = head.next;   //move head over
    			head.prev = null;     //take out the prev link from the first node
     
    			return dataToReturn;
    		}
    	}
     
    	//-----------------------------------
    	//removeLast - removes and returns the last element on the list
    	public E removeLast()
    	{
    		//case 1: is it empty?
    		if (head == null)
    			throw new NoSuchElementException("the list is empty");
     
    		//case 2: if there is only 1 element on the list
    		else if (head == tail)    //already handled the case where they were both null
    		{
    			E dataToReturn = tail.data;    //store the data that will be returned
    			head = tail = null;     //make the list empty
    			return dataToReturn;   //return the data
    		}
     
    		//case 3: if there are lots of elements on the list
    		else
    		{
    			E dataToReturn = tail.data;    //store the data that will be returned
    			tail = tail.prev;
    			tail.next = null;     //last element no longer points at anything
     
    			return dataToReturn;
    		}
    	}
     
    	//-----------------------------------
    	//remove - removes the first instance of the "doomed" element
    	public boolean remove(E doomed)
    	{
    		//case 1: list is empty
    		if (head == null)
    			return false;    //means it did not find it
     
    		//case2: list only has 1 element
    		else if (head == tail)
    			if (head.data.equals(doomed))
    			{
    				removeFirst();
    				return true;
    			}
    			else
    				return false;
     
    		//case3: doomed is at the front of the list
    		else if (head.data.equals(doomed))
    		{	removeFirst();   //don't do anything with what it returned
    			return true;
    		}
     
    		//case4: doomed is at the end of the list
    		else if (tail.data.equals(doomed))
    		{	removeLast();   //don't do anything with what it returned
    			return true;
    		}
     
    		//case5: doomed is in the middle of the list somewhere
    		else
    		{
    			DLLNode<E> ptr = head;
    			while (ptr != null && !ptr.data.equals(doomed))
    			{
    				ptr = ptr.next;
    			}
     
    			//should stop at the node
    			if (ptr == null)   //if if did not find it
    				return false;
    			else   //found it!
    			{
    				ptr.prev.next = ptr.next;    //move the next link so it goes around the doomed node
    				ptr.next.prev = ptr.prev;	//move the prev link so it goes around the doomed node
    				return true;
    			}
    		}
    	}
     
    	//-----------------------------------
    	//recursiveToString() - "starting" method for recursively traversing a list and returning its contents
    	//                                   it just calls the recursive version.
    	public String recursiveToString()
    	{
    		return recursiveToString2(head);
    	}
     
    	//-----------------------------------
    	//recursiveToString2 - recursively traverses whatever list is is passed by calling itself
    	private String recursiveToString2(DLLNode start)
    	{
    		if (start == null)
    			return "";
    		else
    		{
    			//this way returns the contents backwards
    			return recursiveToString2(start.next) + "  " + start.data;	//backwards - recursion then data
    			//return start.data + "  " + recursiveToString2(start.next);	//forwards - data then recursion
    		}
    	}
     
     
     
    }
     
    	//-----------------------------------
    	//This is the DLLNode class which will implement the nodes that make up an DLList
    	class DLLNode<E>
    {
    	//data
    	public E data;
    	public DLLNode<E> next;
    	public DLLNode<E> prev;
     
    	//constructor
    	public DLLNode(E theData)
    	{
    		data = theData;
    		next = prev = null;
    	}
     
    	//methods
    	//toString - returns its representation as a String
    	public String toString()
    	{
    		return "" + data;
    	}
     
     
     
    }
    Heres a tester if you want that-
    public class PartialTesterInfiniteInt
    {
    	public static void main(String[ ] args)
    	{
    		InfiniteInt int1;
    		InfiniteInt int2;
    		InfiniteInt int3;
     
    		System.out.println("Test1: building an InfiniteInt with default constructor (your toString must work)");
    		try
    		{
    		 	int2 = new InfiniteInt();
    		 	System.out.println("Expected: 0");
    		 	System.out.println("Got:      " + int2);
    		}
    		catch(Throwable ex)
    		{
    			ex.printStackTrace();
    		}
     
    		System.out.println("\nTest2: building an InfiniteInt with 6 numbers (your toString must work)");
    		try
    		{
    		 	int2 = new InfiniteInt("543534");
    		 	System.out.println("Input to constructor: \"543534\"...");
    		 	System.out.println("Expected: 543,534");
    		 	System.out.println("Got:      " + int2);
    		}
    		catch(Throwable ex)
    		{
    			ex.printStackTrace();
    		}
     
    		System.out.println("\nTest3: building an InfiniteInt with 7 numbers (your toString must work)");
    		try
    		{
    		 	int2 = new InfiniteInt("5435341");
    		 	System.out.println("Input to constructor: \"5435341\"...");
    		 	System.out.println("Expected: 5,435,341");
    		 	System.out.println("Got:      " + int2);
    		}
    		catch(Throwable ex)
    		{
    			ex.printStackTrace();
    		}
     
    		System.out.println("\nTest4: does your toString fill in 0's correctly?");
    		try
    		{
    		 	int2 = new InfiniteInt("120100000");
    		 	System.out.println("Input to constructor: \"120100000\"...");
    		 	System.out.println("Expected: 120,100,000\"");
    		 	System.out.println("Got:      " + int2);
    		}
    		catch(Throwable ex)
    		{
    			ex.printStackTrace();
    		}
     
    		System.out.println("\nTest5: trying to create an InfiniteInt with an illegal input");
    		try
    		{
    			System.out.println("input to constructor: \"111a1\"...");
    			System.out.println("Expected: java.lang.IllegalArgumentException: <your message>");
    			int1 = new InfiniteInt("111a1");
    			System.out.println("Got:      " + "no exception");
    		}
    		catch(Throwable ex)
    		{
    			System.out.println("Got:      " + ex);
    		}
     
    		int1 = new InfiniteInt("24");
    		int2 = new InfiniteInt("5");
    		int3 = new InfiniteInt("24");
    		Integer int4 = new Integer(24);
    		System.out.println("Should got 1: ");
    		System.out.println( "Got " + int1.compareTo(int2));    //should print 1
    		System.out.println(int2.compareTo(int1));    //should print -1
    		System.out.println(int1.compareTo(int1));    //should print 0
    		System.out.println(int1.compareTo(int3));    //should print 0
    		//System.out.println(int1.compareTo(int4));    //throw a new instance of ClassCastException
     
     
     
    		System.out.println("\nTest6: a simple add");
    		try
    		{
    			int1 = new InfiniteInt("23");
    		 	int2 = new InfiniteInt("15");
    		 	int3 = InfiniteInt.add(int1, int2);
    		 	System.out.println("adding 23+15...");
    		 	System.out.println("Expected: 38");
    		 	System.out.println("Got:      " + int3);
    		}
    		catch(Throwable ex)
    		{
    			ex.printStackTrace();
    		}
     
    		System.out.println("\nTest7: a simple add with a carry in the calculation");
    		try
    		{
    			int1 = new InfiniteInt("23");
    		 	int2 = new InfiniteInt("19");
    		 	int3 = InfiniteInt.add(int1, int2);
    		 	System.out.println("adding 23+19...");
    		 	System.out.println("Expected: 42");
    		 	System.out.println("Got:      " + int3);
    		}
    		catch(Throwable ex)
    		{
    			ex.printStackTrace();
    		}
     
    		System.out.println("\nTest8: a simple add with a final carry");
    		System.out.println("\nTest9: the example from the requirements");
    		System.out.println("\nTest10: adding two HUGE ints (to be sure it does not use regular ints to do it");
    		System.out.println("\nTest11: telling a new InfiniteInt(\"24\") to compareTo(itself)");
    		System.out.println("\nTest12: telling a new InfiniteInt(\"24567\") to compareTo(new InfiniteInt(\"6\") - more nodes...");
    		System.out.println("\nTest13: telling a new InfiniteInt(\"6\") to compareTo(new InfiniteInt(\"24567\") - less nodes...");
    		System.out.println("\nTest13: telling a new InfiniteInt(\"24\") to compareTo(a different new InfiniteInt(\"24\")");
    		System.out.println("\nTest13: telling a new InfiniteInt(\"24\") to compareTo(a new Integer(24))");
    	}
     
     
    }

    I asked my professor the same question and his response confused me even more heres his response-

    "Right now, the DLList node's data will hold an Object. That is because you are USING a new DLList in your InfiniteInt class, but are not using Generics, so it just figures it will hold an Object.

    But it logically SHOULD hold an int, and that is accomplished by having it hold things of type Integer. So when you use a DLList, be sure it is defined to only contain <Integer> and ints should all work automatically as data.

    Also, check the requirements. Your InfiniteInt class is both a subclass of DLList and has data that is a DLList. You should do one or the other. Usually (in my opinion), having it as the data is preferable (it limits the use of the class to what you specifically define as its methods), but I believe that the requirements said to make it a subclass this time.

    So using Generics should help out with this problem..."

Similar Threads

  1. Java program which can list all files in a given directory
    By JavaPF in forum Java Programming Tutorials
    Replies: 8
    Last Post: July 9th, 2013, 03:38 AM
  2. Which collection is best to do mathematical operation on it?
    By Sterzerkmode in forum Java Theory & Questions
    Replies: 1
    Last Post: May 7th, 2009, 04:48 AM
  3. Recursive function based on Linked list
    By rosh72851 in forum Collections and Generics
    Replies: 1
    Last Post: March 9th, 2009, 06:23 PM
  4. String substring, concatenation operation on linked list
    By oaks12 in forum Collections and Generics
    Replies: 1
    Last Post: January 15th, 2009, 07:12 AM
  5. Retrieving BFS code's adjacency list
    By moose4204l in forum Collections and Generics
    Replies: 0
    Last Post: October 20th, 2008, 06:30 PM