Native Java 8 (one line)
With Java 8, int[] can be converted to Integer[] easily:
int[] data = {1,2,3,4,5,6,7,8,9,10};
// To boxed array
Integer[] what = Arrays.stream( data ).boxed().toArray( Integer[]::new );
Integer[] ever = IntStream.of( data ).boxed().toArray( Integer[]::new );
// To boxed list
List<Integer> you = Arrays.stream( data ).boxed().collect( Collectors.toList() );
List<Integer> like = IntStream.of( data ).boxed().collect( Collectors.toList() );
As others stated, Integer[] is usually not a good map key.
But as far as conversion goes, we now have a relatively clean and native code.
Native Java 8 (one line)
With Java 8, int[] can be converted to Integer[] easily:
int[] data = {1,2,3,4,5,6,7,8,9,10};
// To boxed array
Integer[] what = Arrays.stream( data ).boxed().toArray( Integer[]::new );
Integer[] ever = IntStream.of( data ).boxed().toArray( Integer[]::new );
// To boxed list
List<Integer> you = Arrays.stream( data ).boxed().collect( Collectors.toList() );
List<Integer> like = IntStream.of( data ).boxed().collect( Collectors.toList() );
As others stated, Integer[] is usually not a good map key.
But as far as conversion goes, we now have a relatively clean and native code.
If you want to convert an int[] to an Integer[], there isn't an automated way to do it in the JDK. However, you can do something like this:
int[] oldArray;
... // Here you would assign and fill oldArray
Integer[] newArray = new Integer[oldArray.length];
int i = 0;
for (int value : oldArray) {
newArray[i++] = Integer.valueOf(value);
}
If you have access to the Apache lang library, then you can use the ArrayUtils.toObject(int[]) method like this:
Integer[] newArray = ArrayUtils.toObject(oldArray);
Videos
Start with a result of 0. Loop through all elements of your int array. Multiply the result by 10, then add in the current number from the array. At the end of the loop, you have your result.
- Result: 0
- Loop 1: Result * 10 => 0, Result + 1 => 1
- Loop 2: Result * 10 => 10, Result + 2 => 12
- Loop 3: Result * 10 >= 120, Result + 3 => 123
This can be generalized for any base by changing the base from 10 (here) to something else, such as 16 for hexadecimal.
You have to cycle in the array and add the right value. The right value is the current element in the array multiplied by 10^position.
So: ar[0]*1 + ar[1]*10 + ar[2] *100 + .....
int res=0;
for(int i=0;i<ar.length;i++) {
res=res*10+ar[i];
}
Or
for(int i=0,exp=ar.length-1;i<ar.length;i++,exp--)
res+=ar[i]*Math.pow(10, exp);
With streams added in Java 8 we can write code like:
int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();
Thought process:
The simple
Stream#toArrayreturns anObject[]array, so it is not what we want. Also,Stream#toArray(IntFunction<A[]> generator)which returnsA[]doesn't do what we want, because the generic typeAcan't represent the primitive typeintSo it would be nice to have some kind of stream which would be designed to handle primitive type
intinstead of the reference type likeInteger, because itstoArraymethod will most likely also return anint[]array (returning something else likeObject[]or even boxedInteger[]would be unnatural forint). And fortunately Java 8 has such a stream which isIntStreamSo now the only thing we need to figure out is how to convert our
Stream<Integer>(which will be returned fromlist.stream()) to that shinyIntStream.Quick searching in documentation of
Streamwhile looking for methods which returnIntStreampoints us to our solution which ismapToInt(ToIntFunction<? super T> mapper)method. All we need to do is provide a mapping fromIntegertoint.Since
ToIntFunctionis functional interface we can also provide its instance via lambda or method reference.Anyway to convert Integer to int we can use
Integer#intValueso insidemapToIntwe can write:mapToInt( (Integer i) -> i.intValue() )(or some may prefer:
mapToInt(Integer::intValue).)But similar code can be generated using unboxing, since the compiler knows that the result of this lambda must be of type
int(the lambda used inmapToIntis an implementation of theToIntFunctioninterface which expects as body a method of type:int applyAsInt(T value)which is expected to return anint).So we can simply write:
mapToInt((Integer i)->i)Also, since the
Integertype in(Integer i)can be inferred by the compiler becauseList<Integer>#stream()returns aStream<Integer>, we can also skip it which leaves us withmapToInt(i -> i)
Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:
List<T>.toArraywon't work because there's no conversion fromIntegertoint- You can't use
intas a type argument for generics, so it would have to be anint-specific method (or one which used reflection to do nasty trickery).
I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(
Even though the Arrays class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).
I am making an if statement in a while loop.
I know I need
if (Integer.parseInt(array[i]) == //what do i put here
??
Thank you
The immediate problem is due to you using <= temp.length() instead of < temp.length(). However, you can achieve this a lot more simply. Even if you use the string approach, you can use:
String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
You need to make the same change to use < newGuess.length() when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]. The vast majority of for loops I write use < in the condition, rather than <=.
You don't need to convert int to String. Just use % 10 to get the last digit and then divide your int by 10 to get to the next one.
int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
array.add(temp % 10);
temp /= 10;
} while (temp > 0);
This will leave you with ArrayList containing your digits in reverse order. You can easily revert it if it's required and convert it to int[].