Java return arrays - java

I'm having trouble returning arrays from a custom method. It compiles fine but I get back:
[Ljava.lang.String;#20cf2c80
Press any key to continue . . .
I use:
System.out.println(getItem(1));
code:
public static String[] getItem(int e) {
String[] stats = new String[7];
String name = "Null";
String desc = "None";
String typeOf = "0";
String attackAdd = "0";
String defenseAdd = "0";
String canSell = "true";
String canEat = "false";
String earnedCoins = "0";
if (e == 1) {
name = "Pickaxe";
desc = "Can be used to mine with.";
typeOf = "2";
}
return new String[] { name, desc, typeOf};
}
Help? :\

The toString() method of an array object actually doesn't go through and produce a string representation of the contents of the array, which is what I think you wanted to do. For that you'll need Arrays.toString().
System.out.println(Arrays.toString(getItem(1)));
The notation [Ljava.lang.String is Java code for a String array - in general, the default string representation of an array is [L followed by the type of the array's elements. Then you get a semicolon and the memory address (or some sort of locally unique ID) of the array.

That's not an error. The JVM simply prints the address of the array since it doesn't print its content. Try this and see what happens now?
System.out.println(getItem(1)[0]);

On Object.toString()
The reason why you're getting such string is because arrays simply inherit and not #Override the Object.toString() method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character #, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
To return a String representation of an array that lists its elements, you can use e.g. Arrays.toString, and for "multidimensional" arrays Arrays.deepToString
Related questions
toString() in Java
Simplest way to print an array in Java
On deepEquals and deepToString for "multidimensional" arrays:
Java Arrays.equals() returns false for two dimensional arrays.
On defining your own type
It needs to be said that your usage of String[] is not the best design choice.
Things would be so much better had you defined your own class BasicItem supported by various enum, with as many final fields as is practical to enforce immutability; perhaps something like this:
public enum ItemType {
KNIFE, SWORD, AXE;
}
public enum Attribute {
SELLABLE, EDIBLE;
}
public class BasicItem {
final String name;
final String desc;
final ItemType type;
final int attackAdd;
final int defenseAdd;
final Set<Attribute> attributes;
//...
}
You should really take advantage all the benefits of good object-oriented design.
See also
Effective Java 2nd Edition
Item 50: Avoid strings where other types are more appropriate
Item 25: Prefer lists to arrays
Item 30: Use enums instead of int constants
Item 32: Use EnumSet instead of bit fields
Item 15: Minimize mutability
Java Tutorials/Enums
Java Tutorials/Object Oriented Programming Concepts

Related

Java String "".value

I have been going through String class in Java in depth.
String in Java is backed by character array.
To create strings that have initial values, we call the constructor as:
/* String creation */
String s = new String("example");
The constructor code in the String class is:
public String(String original) {
this.value = original.value;
}
Can some one please explain me the logic of "original.value". From the source code, I understand it returns character array. But how java generates it?
The "foo" syntax has already constructed a String instance, it's syntactic sugar so that you don't have to write:
String foo = new String(new char[]{'f', 'o', 'o'});
So by the time you call new String("foo") you've already constructed a string once, and are now creating a copy of the first string - not "creat[ing] strings that have initial values".
Effective Java: Item 5 discusses this in more detail, and discourages ever using the new String(String) constructor.

Convert a String representation of Object back to an Object of original type in java

I am using type conversion given below in my project.
**
ArrayList<Object> arr=new ArrayList<Object>();
String str=arr.toString();
**
I want to convert field str back into ArrayList<Object> type.
How to go through?
thanks for Help
You ought to be using the Serializable interface, ObjectOutputStream / ObjectInputStream and byte[] to String conversion such as DatatypeConverter.parseBase64Binary / DatatypeConverter.printBase64Binary
toString() is a protocol. It is defined to produce some string or another. It is not defined to produce a string reversible to an object. Many classes toString methods are designed to produce human readable results, which are nearly guaranteed to not be reversible.
The Java technology universe contains a number of mechanisms for serializing objects into bytes that can be stored or transmitted and then deserialized into objects. These include the built-in Java Object Streams, the build-in Java JAX-B XML marshal/unmarshaling technologies, and then open-source alternatives just as Jackson for mapping to and from Json or Yaml, and many others.
The only way to do this, is to Override the toString() method of the Object in your ArrayList. Say your object has 2 attributes: int size and String name. Your constructor would possible be
public YourObject(int size, String name){
this.size = size;
this.name = name;
}
Now you override your object:
#Override
public String toString(){
return Integer.toString(this.size) + "#" + this.name;
}
In order to create the object again, you will also need another constructor or setter:
public YourObject(String attributes){
String[] parts = attributes.split("#");
this.size = Integer.parseInt(parts[0]);
this.name = parts[1];
}
To go from object to string and back:
List<YourObject> arr; //Initialise this array
List<String> arrStrings = new ArrayList<String>();
//Convert to list of strings
for (YourObject yourObject : arr){
arrStrings.add(yourObject.toString());
}
//Convert it back
List<YourObject> yourObjects = new ArrayList<YourObject>();
for (String converted : arrStrings){
yourObjects.add(new YourObject(converted));
}
If you wish to use a native object, create your own object and extend the native.
Other than that, there is no way to do what you want. And note that this is very prone to error! So be sure to check for length of strings, sizes of arrays and whatnot.

What does the mere name of objects in java imply (Array, ArrayList ) [duplicate]

This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 8 years ago.
I am switching over from C to java programming gradually. While doing so I am confused while understanding the following scenario:
I have following Java Code:
ArrayList<Integer> myList = new ArrayList<Integer>();
for(int j = 0 ; j < 10 ;j++){
myList.add(j);
}
System.out.println(myList);
the o/p is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
According to my understanding what I have here is an object(myList) of type ArrayList.
Now I tried to do the same with an Array object: The same code but replacing Arraylist with an Array:
int [] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};
System.out.println(Arr);
I get Garbage values. Why is this so? What is the difference between Array and ArrayList?
As in C , the name of the array is sort of a pointer. (IT has the address of the first element) , So in Java , what does the mere names of the object imply ?
Address or Reference ?
What is the difference?
Why do I get varied results in case of Array and ArrayList?
Although all parts of the question have been answered in different posts, I'd like to address your specific wording.
First, it is recommended that you declare your list type as an interface and initialize it as an implementation:
List<Object> list = new ArrayList<Object>();
List<Object> list = new ArrayList<>(); // JDK 7 or later allows you to omit the generic type.
You can implement a List interface with several implementations (ArrayList, LinkedList...). See the collection tutorial.
What is the difference between Array and ArrayList?
ArrayList is a class, see the API. it serves as an implementation for the List interface, see the API. These are part of the Java Collections Framework.
An array is not a class as the ArrayList is, but both an array and an instance of a class are objects. Be careful with uppercasing Array, as it is a different class.
I get garbage values. Why is this so?
Why do I get varied results in case of Array and ArrayList?
This has to do with the println method. It automatically calls the toString method of the argument passed into it. The toString method is defined for the Object class which superclasses all other classes, thus they all inherit it. Unless the subclass overrides the inherited method, it retains the implementation of its superclass. Let's look at what it does for Object:
public String toString()
Returns a string representation of the
object. In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the
class of which the object is an instance, the at-sign character `#',
and the unsigned hexadecimal representation of the hash code of the
object. In other words, this method returns a string equal to the
value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Emphasis mine. As you can see, that's the "garbage" you get when printing the array variable. Since arrays are not classes, they cannot override this method (arrays can invoke all the methods of Object, although they don't subclass it in the usual way). However, the subclass AbstractCollection of Object overrides this:
public String toString()
Returns a string representation of this
collection. The string representation consists of a list of the
collection's elements in the order they are returned by its iterator,
enclosed in square brackets ("[]"). Adjacent elements are separated by
the characters ", " (comma and space). Elements are converted to
strings as by String.valueOf(Object).
Since ArrayList is a subclass of AbstractList, which is a subclass of AbstractCollection (and they do not override toString), you get the "concise but informative representation that is easy for a person to read".
There are some fine points as to how the JVM handles arrays, but for the sake of understanding the output from the developer's point of view, this is enough.
In java, a name of a variable is a reference to the variable (if we compare to c++). When you call println on myList you in-fact call the toString() method of ArrayList which is inherited from Object but overridden to give meaningful print. This method is inherited from Object because ArrayList is a class and all classes extend Object and thus have the method toString.
You don't have this trait with native arrays which are primitives so what you get is the default object representation (virtual memory address).
You can try something like this:
public class TestPrint {
private String name;
private int age;
public TestPrint(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name;}
public int getAge() { return age; }
}
Then try println(new TestPrint("Test", 20)); - This will print something similar to what you got with the array.
Now, add a toString() method:
#Override
public String toString() {
return "TestPrint Name=" + name + " Age=" + age;
}
And call println(new TestPrint("Test", 20)); again and you'll get TestPrint Name=Test Age=20 as the output.
Just to further explain why this happens - the method println has an overload that accepts something of type Object. The implementation of this method calls toString to print the object (this is very schematic explanation of course).
In Java everything is a pointer, but depending on what a variable is pointing, the behavior can change.
int[] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] is an array of a primitive type (not of a class type), and it does not contains any information about its 'string representation', so when you want to print the variable as you have done (System.out.println(Arr);), what is printed out it is simply a string representation suitable for any kind of object, like its hashcode (it is not garbage).
While with:
ArrayList<Integer> myList = new ArrayList<Integer>();
you are creating an object of the (generic) class ArrayList<>: this overrides the method (function in C) toString() that specify how print gracefully the content of the ArrayList itself (the method is really basic: it simply iterate over all the items contained, create a string and print it).
When you call System.out.println(myList); the method toString() (which return a String) is implicitly called, and therefore the string created by the method will be printed, as you have shown.

toString in the java code

The following is my java code snippet:
static String sortChars(String s) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
return chars.toString();
}
I invoke above function by using:
String result = sortChars(s);
But the result does not meet my expectation:for example,the s="are", the result="aer". However, when I use:
return new String(chars)
It works.
Could somebody tell me the reason of it. Thanks
Since char[] class does not override the default Object's toString() implementation, it does not return a string composed by the characters in the char array, but the char[] class name + hash code. For example: arr[C#19821f.
toString() returns a string representation of the Object. You can look at it as a description of the object.
new String(chars) will give you a String with the content of the char array.
Use toString() if you want to represent an Object to the user or in a log, use new String() if you want to get a String object that is the same as the content of your array
Note that, among the constructors for a Java String is one that accepts a character array. That converts the character array into a string as you would expect, and it is the correct choice for what you are doing.

Generic trim function in java?

i have a requirement, where i need to develop a single method which accepts any type of paramter(String or Integer etc) and applies trim() to remove leading and trialing spaces. please help me how to write generic method to achieve this?
Thanks!
Java has strictly defined types, it's not PHP or Javascript. Integer does not have spaces. Simply use trim() method of String object. If your 'integer' is actually a string, do (String.valueOf(x)).trim()
It does not make a lot of sense, but here it goes:
public String trim(Object o) {
if (o != null) {
return o.toString().trim();
}
return null;
}
if an integer is like 12345---. --- indicates 3 spaces. how can i remove? do i need to convert it to string before trimming?
If an 'integer' has trailing spaces, it is already the string representation of the integer, not the integer itself. Therefore:
String i = "12345 ";
String trimmed = i.trim();
By contrast, the following is simply not legal
int i = "12345 "; // compilation error
and a string representation of an integer produced like this:
String i = String.valueOf(12345);
will not have leading or trailing whitespace.
In java, all objects have .toString() method which returns string representation of that object.
You can then call .trim() method on that string, so your function may look like this:
public static String trimAny(Object o) {
return o.toString().trim();
}

Categories