Just curious, but when I try to use this to reverse an array it always spits out some incoherent gibberish instead of the array reversed, such as [I#43256ea2. Any ideas as to why it does this?
public class Fiddle {
public static void main(String[] args) {
int[] number = {1,2,3,4,5};
System.out.println(reverse(number));
}
public static int[] reverse(int[] a) {
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[a.length-1-i] = a[i];
}
return b;
}
}
Thanks for any ideas as to why this is happening (it's probably because I'm forgetting something though).
Use the utility method java.util.Arrays.toString(int[]):
System.out.println(Arrays.toString(reverse(number)));
Array classes do not override Object.toString(), meaning they use the default implementation provided by Object, which is "type#hashcode_in_hex". The String representation of the type int[] is [I, which is why you are seeing this "incoherent gibberish."
Try this:
System.out.println(Arrays.toString(reverse(number)));
It's one of the "mistakes" of java - you have to use Arrays.toString() otherwise you get the default toString() from Object, which produces output like you're seeing,
You are printing the hash of the array. you should do something like
for(int i: reverse(number)){
System.out.println(i);
}
Commons.lang
ArrayUtils.reverse(int[] array)
Done.
Related
Hi and thanks for noticing my problem. I want to write a method that can be used by different types of arrays. But my code always looks like this:
public int indexOf_1(int[] a,int b){
//Find the first matched result and return, otherwise report -1
int index = -1;
for(int j=0;j<a.length;j++){
if (a[j]==b)
{index=j;}
}
return index;
}
public int indexOfChar_1(char[] a,int b){
//Consider merged to the previous method?
int index = -1;
for(int j=0;j<a.length;j++){
if (a[j]==b)
{index=j;}
}
return index;
}
That seems to be redundant and I'm completely uncomfortable with such code duplication. Is there any way to write a searching method for all kinds of array to avoid repeating in this case? Thanks!
Unfortunately because the way arrays and the JVM work, this can't be reduced. Not even generics can help since int[] cannot be safely cast to Object[] without explicit conversion.
This looks like a common util function. If you're not comfortable with the code duplication, you can consider using one of the many libraries which provide this functionality. Guava and Commons-Lang are a few.
Guava puts them in the class relevant to the primitive type. Commons-Lang arranges them in the ArrayUtils class
e.g.
Bytes.indexOf(byteArray, (byte) 2);
Ints.indexOf(intArray, 22);
ArrayUtils.indexOf(intArray, 6);
Well you could use Object[] but you might not want to use ==, since it will compare identity of objects instead of values, instead you probably want to use .equals(). (Unless you know the value will always be a char or int) Perhaps this:
public int indexOf(Object[] a, int b) {
int index = -1;
for (int j = 0; j < a.length; j++) {
if (a[j].equals(b)) {
index = j;
}
}
return index;
}
public static <T> int index_Of(Object[] input,T value){
//Find the first matched result and return, otherwise report -1
for(int j=0;j<input.length;j++){
if(input[j].equals(value))
return j;
}
return -1;
}
You can generalize you method to deal with all kind of arrays. However, please pay more attention to the type. If you want to use Object referring to primitive type, when declaring a primitive type array, you need to use reference type. For example,
Character [] a = new Character[]{'a','b','c'};
DO NOT use char, since it will compile error when type checking.
I try to assign an array of numbers from 1 to 10 using the code below. Basically I am stuck on how to return an array. Do I need a toString method ?
package arrays1;
import java.util.Arrays;
public class Arrays1 {
/**
* #param args the command line arguments
*/
private int[] numbers;
private int DEFAULT_SIZE = 10;
public Arrays1(int size){
numbers = new int[DEFAULT_SIZE];
}
public int[] add(int[] n)
{
for(int i=0; i<numbers.length; i++){
numbers[i]=n[i];}
return numbers;
}
public int[] getValues(){
return numbers;
}
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
System.out.println(A.getValues());
}
}
How do I return contents of an array from this code? Do I need to create a new object?
A.getValues() is returning a pointer to the integer array numbers object, which is probably the output you're seeing. You don't need a new object, just use the one you made, Arrays1 A, and iterate over its contents, so something like this:
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
for (int i = 0; i < A.getValues().length; i++){
System.out.println(A.numbers[i]);
}
}
Yes, a toString method would be useful to serialize the contents of the numbers array to a String. But in this case, you should call it like this:
Arrays1 a = new Arrays1(9);
System.out.println(a); // it is an implicit call to toString()
Another acceptable alternative is to let the serialization to the client's responsibility. In this case, the client should rely on the getValues() method, and serialize it by itself:
Arrays1 a = new Arrays1(9);
System.out.println(Arrays.toString(a.getValues()));
Another lesser detail: Review your constructor: It does not use the parameter size, and that can be confusing.
Effective java 2, Item 42 propose an elegant way for a method take at least one argument, and fail at compile time if the input is empty. The code is shown below in the min() method, however I am wondering what is the elegant way to call this method, because now simply passing list will trigger an compiler error.
public class OneOrMoreArgs {
public static int min(int firstArg, int... remaining){
// but then how do you call the function with a int[] ?
int _min = firstArg;
for(int x: remaining){
if(_min < x ){
_min = x;
}
}
return _min;
}
public static int sum(int... list){
int s = 0;
for(int a: list){
s += a;
}
return s;
}
public static void main(String []args){
int[] list = {1,2,3,4,5};
System.out.println(OneOrMoreArgs.sum(list));
System.out.println(OneOrMoreArgs.min(list));
}
}
Well, the elegant way to call it would be to do
OneOrMoreArgs.min(1, 2, 3, 4, 5);
If you need to pass in an array, you could add an additional method signature like this:
public static int min(int[] args){
if (args == null || args.length < 1) {
throw new IllegalArgumentException("... some error message...");
}
return min(args[0], Arrays.copyOfRange(args, 1, args.length));
}
It needs to be noted that:
This solution is inefficient as it requires the array to be copied.
The check is executed at runtime instead of compile time, so you lose the benefits of the solution proposed by Item 42.
It looks like for your use case, you're better off just declaring a method that takes an array parameter, like the sum() in your example.
This method insert takes as input int[] array, int element, and int index, which inserts element into the index position of array. Since an array is not resizable, the method shifts every element over to the right of the array by one. The element at the end is removed from the array. The method returns void.
public class ShiftElements {
public static void insert(int[] array, int element, int index)
{
for (int i = array.length-1; i > index; i--)
{
array[i] = array[i-1];
}
array[index] = element;
}
}
To test if this method works, I changed the return type to int[] and wrote a main method to print array:
public class ShiftElements {
public static int[] insert(int[] array, int element, int index)
{
for (int i = array.length-1; i > index; i--)
{
array[i] = array[i-1];
}
return array;
}
public static void main(String[] args) {
System.out.print(insert(4,5,3));
}
}
I am having problems, getting this print statement to work. It's probably something simple, but I've been up for two days studying for finals so I'm pretty braindead.
I'm pretty sure I called the insert method just fine, but I think my issue is that I'm not properly inputting the type int[]. I'm not sure how I'm supposed to do this.
1) The first parameter of insert is an array of int, not an int. You must call :
insert(new int[]{4},5,3)
2) you can't print an array : so use :
println(Arrays.toString(insert(...)))
I guess what you are looking for is :
int[] i = new int[5];
System.out.print(java.util.Arrays.toString(insert(i,5,3)));
Apart from the use of java.util.Arrays.toString method Watch out the parameters that you are passing in insert method:
first parameter should be an array of int. But you are passing an int.
System.out.print(insert(4,5,3));
That statement does not pass a array of integers, you only passed and integer 4. You would need to pass, as your function is defined, int[], int, int.
System.out.print(insert(new int[4],5,3));
You made a call to insert(int,int,int) eventhough your signature for insert is insert(int[],int,int). For instance, calling insert with an array literal would be like so:
insert(new int[]{1,2,4,5}, 3, 2);
Additionally, System.arraycopy is a much faster and elegant way to copy arrays. You also seem to have forgotten to set the element at its index within your second example:
public static int[] insert(int[] array, int element, int index)
{
// Use arraycopy to shift all the elements by one, running over the last index
System.arraycopy(array, index, array, index+1, array.length-index-1);
// Set the appropriate index in the array to the specified value
array[index]=element;
return array;
}
If you then run the following, you will get your expected output:
int[] array = {1, 2, 4, 5};
insert(array,3,2); // array is now {1,2,3,4}
System.out.println(java.util.Arrays.toString(array));
If you are looking to print the array then the most laymen procedure is to return the particular array and loop throw it to print its element. eg:
public static void main(String[] args) {
int []solution= insert(new int[4],5,3);
for(int i=0;i<solution.length;i++)
{
System.out.println(solution[i]);
}
}
public class Whatever {
static double d;
static char c;
static String[] s;
static char[] b;
static double[] dd;
static Whatever w;
static Whatever[] ww;
public static void main(String[] args) {
System.out.println(Whatever.d); //prints out 0.0
System.out.println("hi"+Whatever.c+"hi"); //prints out hi hi
System.out.println(s); //prints out null
System.out.println(b); //null pointer exception!
System.out.println(Whatever.dd);
System.out.println(Whatever.w);
System.out.println(Whatever.ww);
}
}
Why do I get a null pointer exception?
Please explain in terms of memory if you can, however I have a basic understanding of memory so don't get too in depth either.
Okay, now that you've posted your full code its easier to help! This is normally what happens when you invoke PrintStream.println with a primitive array:
String s = String.valueOf(x);
Which eventually does this:
return (obj == null) ? "null" : obj.toString();
As you can see, the possibility of the supplied object being null is explicitly handled. However, there is a specific overload on the PrintStream class, just for char arrays. Here is a rough trace of the logic:
write(cbuf, 0, cbuf.length);
Where cbuf is the given char array. As you can see, it tries to reference the character arrays length, which will blow up with an NPE if the array is not initialized. It's an odd and unfortunate inconsistency in the implementation.
So now you understand why the NPE is occurring - to fix it simply initialize the char array before trying to print it out.
There's a few problems here:
1. You're not allocating any space for `int x`
2. If you want to print the contents of `x`, it should be `x.toString()`
3. What did you expect the output to be from your sample code?
I'm guessing #3 isn't what you're actually working with, I would suggest you show your real code to get a real answer :)
Hopefully this can clear it up a bit for you.
$ cat Whatever.java
public class Whatever {
static final int MAX = 5;
int[] x = new int[MAX]; // allocate array to sizeof '5'
public Whatever() {
// do stuff
}
public void addStuff() {
for(int i=0; i<MAX; i++)
x[i] = i + 2;
}
public void printX() {
for(int i=0; i<MAX; i++)
System.out.println(i + ": " + x[i]);
}
public static void main(String[] args){
Whatever w = new Whatever(); // new instance of 'Whatever'
w.addStuff(); // add some ints to the array
w.printX(); // print out the array
// print the Array 'x'
System.out.println("Array: " + w.x);
}
}
$ java Whatever
0: 2
1: 3
2: 4
3: 5
4: 6
Array: [I#870114c
The problem is basically rooted in how PrintStream.println(...) is implemented. Except for char[], a primitive array is treated as a java.lang.Object. So the println overload used is println(Object). Underneath, printing an object involves calling the object's toString(). Hence the NPE.
If you want to be defensive of nulls, you should consider using String.valueOf(Object).