0

/*Hello, I tried to write a array class for adding each element by 1, however I couldn't call the toString() method successfully, can anyone help me figure out why? Thanks.

package addArray;

 public class Additioner {



public Additioner(int x[])
{
    addIt(x);
}

public void addIt(int x[])
{
    for (int counter = 0; counter < x.length; counter++)
    {
        x[counter] += 1;
    }
}

public String toString()
{
    String message = ("Some message here.");
    return message;
}
 }

============================================

    package addArray;
    import java.util.*;

    public class Array {

public static void main(String[] args)
{
    int Q[] = {1, 2, 3, 4, 5};
    System.out.println(Arrays.toString(Q));
    
    Additioner x = new Additioner(Q);
    
    
    System.out.println(Arrays.toString(Q));
    System.out.println(Q.toString());
                     }   }

================================================== Result:

[1, 2, 3, 4, 5]

[2, 3, 4, 5, 6]

[I@6d06d69c

Community
  • 1
  • 1
  • Why do you expect anything different from `Q.toString()`? This is _always_ going to be the result when you call `toString()` on an array. – Louis Wasserman Mar 02 '16 at 19:51
  • Thanks for respond. I am just wondering why I couldn't print out the message in my toString() appropriately. I want to add more things like comparison method and which can determine to print more literal information. – SuchCrowMuchWow Mar 02 '16 at 19:58
  • you can't do any of that. You can't add or change the behavior of arrays; they have only the methods they come with, and their `toString()` will always return output like this. You can have other methods you use instead, or wrap them in objects of your own, but that's it. – Louis Wasserman Mar 02 '16 at 19:59
  • Oh, I see the problem now. So if I want to create new methods involving arrays, I must get rid of the signatures like (array[]) which will generate its toString method like array.toString which is conflict with the original toString already existing. Thank you sir. – SuchCrowMuchWow Mar 02 '16 at 20:05
  • Uh. I don't know what you mean, but if you want to create new methods involving arrays, they will have to take arrays as input. You can't make `array.something()` do anything useful. – Louis Wasserman Mar 02 '16 at 20:06
  • OK, so if I create class like: public class (Array[], boolean sth, String sth), will this somehow be helpful to add more info. for printing out? – SuchCrowMuchWow Mar 02 '16 at 20:14
  • You can implement the `toString()` of a class you write however you want, to print out whatever detail you want. – Louis Wasserman Mar 02 '16 at 20:14
  • Oh, never mind. I just put Q.toString() instead of x.toString() confused me so much lol. Thank you sir, at least I learned something from you. – SuchCrowMuchWow Mar 02 '16 at 20:22

0 Answers0