Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error of int cannot be dereferenced?

Tags:

java

arrays

I am getting an error with this constructor, and i have no idea how to fix? I am a beginner at java. This is from an example exercise that i was trying to learn:

/** 
 * Create an array of size n and store a copy of the contents of the
 * input argument
 * @param intArray array of elements to copy 
*/
public IntArray11(int[] intArray)
{
    int i = 0;
    String [] Array = new String[intArray.length];
    for(i=0; i<intArray.length; ++i)
    {
    Array[i] = intArray[i].toString();
    }
}
like image 832
Hotfin Avatar asked Jan 29 '15 11:01

Hotfin


2 Answers

int is not an object in java (it's a primitive), so you cannot invoke methods on it.

One simple way to solve it is using Integer.toString(intArray[i])

like image 176
amit Avatar answered Oct 01 '22 08:10

amit


I would write it more like this

public String[] convertToStrings(int... ints) {
    String[] ret = new String[ints.length];
    for(int i = 0; i < intArray.length; ++i)
        ret[i] = "" + ints[i];
    return ret;
}

Or in Java 8 you might write

public List<String> convertToStrings(int... ints) {
    return IntStream.of(ints).mapToObj(Integer::toString).collect(toList());
}

This uses;

  • Java coding conventions,
  • limited scope for the variable i,
  • we do something with the String[],
  • give the method a meaningful name,
  • try to use consist formatting.

If we were worried about efficiency it is likely we could do away with the method entirely.

String.valueOf(int) is not faster than Integer.toString(int). From the code in String you can see that the String implementation just calls Integer.toString

/**
 * Returns the string representation of the {@code int} argument.
 * <p>
 * The representation is exactly the one returned by the
 * {@code Integer.toString} method of one argument.
 *
 * @param   i   an {@code int}.
 * @return  a string representation of the {@code int} argument.
 * @see     java.lang.Integer#toString(int, int)
 */
public static String valueOf(int i) {
    return Integer.toString(i);
}
like image 45
Peter Lawrey Avatar answered Oct 01 '22 08:10

Peter Lawrey