I need to create my own String
class called MyString
without using default String class/vector API. I have to work on some required methods, and their return types are predetermined. I can add other methods as long as String
is not used.
Expected use would be:
(at main) System.out.println(str.toLowerCase())
- returns lower case of str
When I want to work with toLowerCase()
method with return type MyString
, I can't return the object content but only return the address.
Normally, this problem would require modification of toString()
, but since this method requires return type of String by default, I can't use modification of toString()
for the assignment.
The assignment is supposed to be not so hard and should not require complex extensions. My constructor may be the problem, but I can't specify which part is.
Code
public class MyString {
private char value[];
MyString(char[] arr){
this.value = Arrays.copyOf(arr, arr.length);
}
...
MyString toLowerCase() { // can't change return type
for (int i =0; i<value.length; i++) {
if ((int)value[i] > 64 && (int)value[i] < 91) {
value[i] = (char) (value[i]+32);
}
}
return this; // this returns address, and I can't override toString
}
Problem with System.out.println(str.toLowerCase())
is it ends up calling PrintStream.println(Object o)
, but that method internally at some point calls o.toString()
which uses code inherited from Object#toString()
(since you couldn't override toString
as it expect as result String
which is forbidden in your project) which result in form TypeInfo@hexHashCode
.
This means you can't use System.out.println(MyString)
.
BUT PrintStream
(which instance is held by System.out
) allows us to provide data to print in different forms. In this case you can use println(char[])
. All you need to do is adding to MyString
method like toCharArray()
which would return (preferably a copy of) array of characters held by MyString
class.
This way you can use it like System.out.println(myStringInstance.toCharArray())
so code from your main
method would need to look like
System.out.println(str.toLowerCase().toCharArray());
// ^^^^^^^^^^^--this should return char[]