aspose file tools*
The moose likes Beginning Java and the fly likes casting objects? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "casting objects?" Watch "casting objects?" New topic
Author

casting objects?

Mark Baumeister
Greenhorn

Joined: Sep 27, 2007
Posts: 6
I hope this is an easier question to deal with.

I am trying to pass a reference to a character object (lch) to a constructor
for a different type object (MyList). Please see below.

The StringEditor constructor receives two string objects StringEditor(String left, String right) and converts the characters of the string objects to an array of characters and then converts the individual characters into character objects. I wish to pass these individual character objects to another constructor (i.e. MyList(MyList lst))to create a list of MyList objects . However I cant just write MyList lftCh = new MyList(lch); because the character object is a different type of object. Can anyone tell me how to pass a character object to the MyList constructor below. Do I need to cast the character object as a MyList object before doing so. If so, how would I do this. See below.

Thanks,
MB




public StringEditor(String left, String right) {

char[] leftChars = left.toCharArray();
char[] rightChars = right.toCharArray();
for(int i = 0; i <= left.length() - 1; i++) {
Character lch = new Character(left.charAt(i));

MyList lftCh = new MyList(lch); // I can't do this

}
}

public class MyList {

private int numItems;
private Object item;
private MyList next;
private MyList ref = null;

public MyList() {
next = null;
}

// Effect: new MyList object created that is copy of lst
// Precondition: lst is not null
// Postcondition: an MyList object that is identical to lst exists
public MyList(MyList lst) {
next = lst;

}
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18138
    
  39

Can anyone tell me how to pass a character object to the MyList constructor below.


In order to be able to construct a MyList object, with a character object, you need a constructor that takes a character object.


BTW, are you sure that this is what you want? If mylist is supposed to take many characters, shouldn't you have the capability (a method) that will allow you to add a character to a mylist instance? Or do you want each mylist instance to hold only one character?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: casting objects?
 
Similar Threads
If/Else/Switch Statements
Date Editor
string editor
Sun Cirtification
passing objects to constructors