This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I've come across what appears to be an interesting bug...
For one of my classes, I need to write a program that simulates the old "x students going down a hallway closing lockers every x interval" scenario. However, an interesting twist is that the question requires there to be an equal number of students and lockers up to 100. So I decided to use an array, where the user input a number - which is then used to set up the array size, for-loop conditions, etc. etc... you get the picture, right?
Anyway, my code compiles, but when run it puts out something like:
[I#36ae2282
Someone (in another thread/question/whatever-you-call-it) stated that this is the physical location of the array in the system memory, and to get the actual numbers from the array the .getNums() method would be required. My problem is: the .getNums() method doesn't seem to exist in Java (perhaps it's part of another language?), so what is the next best alternative or solution?
You're printing out the int array, and that's a traditional array's .toString() representation. You may want to use Arrays.toString() for nicer looking output instead.
To print the content of an array either iterate over each element in the array:
int[] array = new int[10];
for(int s : array) System.out.println(s);
// or
for(int i = 0; i < array.length; i++) System.out.println(array[i]);
or use Arrays.toString():
int[] array = new int[10];
System.out.println(Arrays.toString(array));
which will print something like:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Anyway, my code compiles, but when run it puts out something like:
[I#36ae2282
I assume you are trying to print the array like this:
int[] array = new int[10];
System.out.println(array);
array is an object, hence you are calling println(Object) of PrintStream (System.out), which calls toString() on the passed object internally. The array's toString() is similar to Object's toString():
getClass().getName() + "#" + Integer.toHexString(hashCode());
So the output would be something like:
[I#756a7c99
where [ represnts the depth of the array, and I refers to int. 756a7c99 is the value returned from hashCode() as a hex number.
Read also Class.getName() JavaDoc.
Related
This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 1 year ago.
I basically see this in the output screen every time I am trying to set two non-boolean types equal to each other using a binary operator.
What I do not understand is, if the compiler goes on and compiles it but displays [I#60e53b93 (which seems to me to be an address),
is it because it is using arr as an object or is it because it is actually working and the loop is running infinitely?
So what I was trying to do was just experiment with arrays and see what I could do with them because it's been a while since I worked with Java.
So what I basically did was:
int [] arr = {1,2,3,4,5,6};
int[]arar={1,2,3,4,5,6};
while (arar==arr){
arr[0]=2;
}
System.out.println(arr);
and so I was basically expecting a red flag but then the code ran and displayed [I#60e53b93 which I did not understand why?
Can somebody explain this to me and if possible how I can display the array arr even if it is in a continuous loop?
Two things are going on here:
arr will never equal arar because == uses reference equality; since arr and arar can be modified independently, they aren't the same object.
System.out.println(anyArray) will always display output like yours, because arrays don't have a useful toString function.
You can solve both problems by using static methods from Arrays:
while (Arrays.equals(arr, arar)) {
...
}
System.out.println(Arrays.toString(arr));
Because arr is just a reference to an array. It's not the content of the array. The reference holds the memory location where the actual content of the array is. Calling toString() on an Object will by default output its memory location. (toString() will implicitly be called by System.out.println)
Every object in Java has a toString() method. Though you can call System.out.println basically on everything. Some objects have a custom toString implementation and print something useful, and others (like arrays) just print their memory location.
If you want to display the array contents, you have to loop over the array:
for(int elem : arr) {
System.out.println(elem);
}
I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don't know how to use it to add an element in an array. I prefer it without an ArrayList or list. I wonder if the StringBuffer will work on integers.
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List.
Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.
Generally, there is the List<T> interface, which represents a list of instances of the class T. The easiest and most widely used implementation is the ArrayList. Here is an example:
List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("World");
words.add("!");
List.add() simply appends an element to the list and you can get the size of a list using List.size().
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).
What you can do is create a new array one element larger and fill in the new element in the last slot:
public static int[] append(int[] array, int value) {
int[] result = Arrays.copyOf(array, array.length + 1);
result[result.length - 1] = value;
return result;
}
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer), then you can use one of the NIO Buffer classes like java.nio.IntBuffer. These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.
For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.
Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.
Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).
one-liner with streams
Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();
Is it possible to do this? I want to be able to give the user the option to add another element to the array which is set to the length 5 and has already been filled. I believe this will increase the array length by 1? Also, please know that I know how to do this in ArrayList. I want to be able to do this in a normal array.
I heard that Arrays.copyof() can help do this but I don't understand how?
You can't add one more element if your array is filled.
You need to build a bigger array and copy the values from the old array to the new one. That's where Arrays.copyOf comes in handy.
For performance reason, it would be better to add more than 1 empty cell each time you rebuild a new array. But basically, you will build your own implementation of ArrayList.
In an ArrayList you can just add another value without having to do anything. Internally, the ArrayList will create a new, larger array, copy the old one into it, and add the value to it.
If you want to do this with an array, you will need to do this work yourself. As you are thinking, Arrays.copyOf() is a simple way to do that. For instance:
int[] a = {1,2,3,4,5};
System.out.println(a.length); // this will be 5
System.out.println(Arrays.toString(a)); // this will be [1, 2, 3, 4, 5]
int[] b = Arrays.copyOf(a, 10);
System.out.println(b.length); // this will be 10, half empty
System.out.println(Arrays.toString(b)); // this will be [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
import java.util.Arrays;
int[] myArray = new int[]{1,2,3,4,5}; //The array of five
int[] myLongerArray = Arrays.copyOf(myArray, myArray.length + 1); //copy the original array into a larger one
myLongerArray[myLongerArray.length-1] = userInput; //Add the user input into the end of the new array
If you're going to be adding a lot of elements, instead of making the array one element larger each time, you should consider doubling the size of the array whenever it gets full. This will save you copying all of the values over each time.
Here is another example of using copyOf()
List<Object> name = ArrayList<Object>();
name.add(userInput);
It's much better, more efficient. Also has convenient methods for use (especially add(Object), indexOf(Object), get(Object), remove(Object)).
Suppose I have an array of objects from the MyClass class:
MyClass myClassArray[] = {
new MyClass(0, 1),
new MyClass(2, 3),
new MyClass(4, 5),
new MyClass(6, 7)
};
Here, the MyClass constructor fills in two fields, which we shall call field1 and field2. Suppose now that I want to fill in an array containing the value of field1 from each object in myClassArray (so the array will contain the values 0, 2, 4, 6). The following does not work:
field1Array = myClassArray.getField1();
Is there a quick 1-line way to fill in the new array using return codes from methods belonging to objects in the original array? Obviously, I can do this using a for loop, but I'd rather make use of the features of the language, if they exist.
You will need to loop unless you are using Java 8+ which adds lambda expressions to the language, in which case you can map your array to a new array:
int[] field1Array = Arrays
.stream(myClassArray)
.mapToInt(MyClass::getField1)
.toArray();
This is admittedly a theoretical answer since Java 8 will not be officially released until Q1 next year.
Currently there are no other language features than a plain old and simple for loop.
With Java 8 there may be lambda expressions and perhaps some helper method for Collection which will do what you want. But Java 8 is not yet released.
No, as far as I know, in Java, there is no way to call a method on every element of the array, apart from using a loop.
int[] field1 = new int[myClassArray.size()];
for(int i = 0; i < myClassArray.size(); i++){
field1[i] = myClassArray[i].getField1();
}
Your approach has to use a loop (while, here for), because you can't run through an array without one. Sure you can handle each element of the array one by one. But this would be a nightmare for a fair size of elements in the array.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I am trying to write a simple program using the code below to make a single dimensional array that you can then call a value from using the index numbers. I am using java and eclipse as my compiler. Whenever I try to debug or run the program, the full array prints out as this: [I#1fa8d3b.
class Array
{
public static void main(String[] args)
{
int[] MyArray = new int[] {15, 45, 34, 78, 65, 47, 90, 32, 54, 10};
System.out.println("The full array is:");
System.out.println(MyArray);
System.out.println("The 4th entry in the data is: " + MyArray[3]);
}
}
The correct data entry prints out when it is called though. I have tried to look for answers online as to what I should do, but I could not find anything that actually works. I am just starting to learn Java so there could be a very simple answer to this that I am just overlooking. If anyone has any ideas, I would be greatly appreciative.
Java is an object oriented language. When you are calling System.out.print(MyArray); in Java you are actually printing the address of the object on the heap in memory the toString code from it's parent class Object, the code is shown below contributed by the comment from EngFouad, sorry for misspeaking. The weird String you see printed out is the reference the computer uses to find your data when you ask for something associated with the variable MyArray.
As stated by the other answers, to print out the data of your object you can use the Array class's built in .toString() method. This will print the data from the object instead of just the object reference.
System.out.println(Arrays.toString(MyArray);
Correction
Actually it is toString() of the class Object: getClass().getName() + "#" + Integer.toHexString(hashCode()). – Eng.Fouad
Mistake above was corrected thanks for the comments, hate to give the wrong information. I misunderstood it myself. Here is the API reference to see the code:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#toString()
Use:
System.out.println(Arrays.toString(MyArray));
In order to print the array elements.
In your case you used the default Object.toString() implementation, which is not so informative...
Use this instead:
System.out.println(Arrays.toString(MyArray));
API Reference: Arrays.toString(int[])
to print the array you need to use the loop. for example:
for (int i: MyArray){
System.out.print(i + " ")}