• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting objects?

 
Mark Baumeister
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21019
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic