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

8
  • Why do you expect anything different from Q.toString()? This is always going to be the result when you call toString() on an array. Commented Mar 2, 2016 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. Commented Mar 2, 2016 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. Commented Mar 2, 2016 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. Commented Mar 2, 2016 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. Commented Mar 2, 2016 at 20:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.