Java take range from array - java

Does Java have a method of Array drop? In Scala we have: Array.drop(10).take(16) or maybe to take a range of members of an array?
In Java I can only do array[10] for example.

There is Arrays::copyOfRange:
It has three parameters:
original: the source array
from: the starting index, inclusive
to: the end index, exclusive
Not that it returns a new array, meaning that if you change the values of the resulting array, the original array does not change.
The method is overloaded to work for all primitive types and for objects.
Here's an example use:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
final int[] source = IntStream.range(0, 10).toArray()
System.out.println(Arrays.toString(source));
final int[] result = Arrays.copyOfRange(source, 3, 8);
System.out.println(Arrays.toString(result));
}
}
Which prints:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]
For more information, see the docs

I think it's easiest to achieve such semantics by streaming the array:
SomeClass[] sourceArray = /* something */;
SomeClass[] result =
Arrays.stream(sourceArray).skip(10L).limit(16L).toArray(SomeClass[]::new);

Related

I wanted to add an element to my array after sorting the array

Here is my code
import java.util.*;
public class ArrayExample {
public static void main(String[] args) {
Integer arr[] = {5,4,3,2,15,8,9};
List<Integer> list = Arrays.asList(arr);
Collections.sort(list);
System.out.println(list);
list.add(6);// here I am adding 6 to my array.
System.out.println(list);
// Here I should get output as [2,3,4,5,6,8,9,15]
}
}
You can't because this declaration :
List<Integer> list = Arrays.asList(arr);
From documentation :
Arrays.asList Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
This method acts as bridge between array-based and collection-based
APIs, in combination with Collection.toArray(). The returned list is
serializable and implements RandomAccess.
for that you can't add to this list, even if you try to remove list.remove(index); this not work.
so to solve your problem you can use :
List<Integer> list = new ArrayList<>();//declare the list
for(Integer i : arr){
list.add(i);//add element by element to the list
}
Or simply you can use :
List<Integer> list = new ArrayList<>(Arrays.asList(arr));
//----------------------------------^------------------^
If you want the array to stay sorted, you will have to sort it after each insert.
However, using a binary search, you could also find the index i where the item should be inserted and insert it there using list.add(i,6). Which would be more efficient.
No you cannot add, as you are using Arrays.asList(arr);
List<Integer> list = Arrays.asList(arr);
asList returning a fixed-size list, you cannot add any element in that, once the list is formed.
You may get java.lang.UnsupportedOperationException
[2, 3, 4, 5, 8, 9, 15]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at Test.main(Test.java:14)
You can add an element without using a list by using 2 arrays: a source array src and a destination array dest. The destination array will have one more element than the source one. You simply need to copy all the elements of the source array to the destination, and add your new element. Depends on different requirement of your post title & your post body, I added 2 solutions:
Solution 1
This solution add an element to your array AFTER sorting the array, as mentioned in the post title. But please notice that the element added is located at the tail of the new array.
Integer src[] = { 5, 4, 3, 2, 15, 8, 9 };
Integer dest[] = new Integer[src.length + 1];
Arrays.sort(src);
System.out.println(Arrays.toString(src));
// [2, 3, 4, 5, 8, 9, 15]
System.arraycopy(src, 0, dest, 0, src.length);
dest[src.length] = 6;
System.out.println(Arrays.toString(dest));
// [2, 3, 4, 5, 8, 9, 15, 6]
// ^
Solution 2
This solution add an element to your array BEFORE sorting the array. It contains the expected array as mentioned in your code comment in the post body.
Integer src[] = { 5, 4, 3, 2, 15, 8, 9 };
Integer dest[] = new Integer[src.length + 1];
System.arraycopy(src, 0, dest, 0, src.length);
dest[src.length] = 6;
Arrays.sort(dest);
System.out.println(Arrays.toString(dest));
// [2, 3, 4, 5, 6, 8, 9, 15]
// ^
See also:
Sorting methods in Arrays (Java Platform SE 8) - Oracle Help Center
System#arraycopy(Object, int, Object, int, int)

Simple array class working but giving wrong output

I'm doing some Java code challenges and am trying to write the entire class w/ a constructor and main() instead of a regular method just to get some extra practice in. I've tried running it in Eclipse and JGrasp and got the same output: [I#6d06d69c
Does anyone have a clue as to what I'm doing wrong? Thanks in advance for your help :)
/*
Given an int array, return a new array with double the
length where its last element is the same as the original
array, and all the other elements are 0. The original
array will be length 1 or more. Note: by default, a
new int array contains all 0's.
makeLast({4, 5, 6}) → {0, 0, 0, 0, 0, 6}
makeLast({1, 2}) → {0, 0, 0, 2}
makeLast({3}) → {0, 3}
*/
public class MakeLast {
public MakeLast(int[]nums){
int[] result = new int[nums.length *2];
result[result.length-1] = nums[nums.length-1];
System.out.println(result);
}
public static void main(String[] args) {
int[] nums = {3, 5, 35, 23};
new MakeLast(nums);
}
}
result is an array, you cannot print it directly using System.out.println. Instead try the below.
System.out.println(Arrays.toString(result));
If you want more controlled output of the elements in the array, you can iterate through the elements in the array and print them one by one. Also you can check the javadoc for toString method in Object class to see what [I#6d06d69c means.
You can not print the array directly by System.out.println() method in java.
For that you have to use the toString() method present in Array class of util package. Moreover here you can directly use result[7] to see the value.
import java.util.*;
class MakeLast {
public MakeLast(int[]nums){
int[] result = new int[nums.length *2];
result[result.length-1] = nums[nums.length-1];
System.out.println(result.length);
System.out.println(result[7]);
System.out.println(Arrays.toString(result));
}
public static void main(String[] args) {
int[] nums = {3, 5, 35, 23};
new MakeLast(nums);
}
}

Inline Array Definition in Java

Sometimes I wish I could do this in Java:
for (int i : {1, 2, 3, 4, 5})
System.out.println(i);
Unfortunately, I have to do something like this instead:
int [] i = {1, 2, 3, 4, 5};
// ...
My recollection is that C++ has this sort of feature. Is there an OOP replacement for inline array definitions (maybe even to the point of instantiating anonymous classes)?
I think the closest you are gonna get is:
for(int i : new int[] {1,2,3,4})
You could create the int[] array in the for loop.
for (int i : new int[] {1, 2, 3, 4, 5}) {
...
}
Here you are making an anonymous int array, which is the closest thing to what you want. You could also loop through a Collection.
Note that this question has nothing to do with OOP. It's merely a matter of syntax. Java supports anonymous arrays/objects just like C++.
You don't have to create a separate variable for this. The syntax {1, 2, ...} is valid only for declarations, but you can always say new int[] {1, 2, ...}:
for (int i : new int[] {1, 2, 3, 4, 5})

Print multi-dimensional array using foreach [duplicate]

This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 6 years ago.
How to print multi-dimensional array using for-each loop in java? I tried, foreach works for normal array but not work in multi-dimensional array, how can I do that? My code is:
class Test
{
public static void main(String[] args)
{
int[][] array1 = {{1, 2, 3, 4}, {5, 6, 7, 8}};
for(int[] val: array1)
{
System.out.print(val);
}
}
}
Your loop will print each of the sub-arrays, by printing their address. Given that inner array, use an inner loop:
for(int[] arr2: array1)
{
for(int val: arr2)
System.out.print(val);
}
Arrays don't have a String representation that would, e.g. print all the elements. You need to print them explicitly:
int oneD[] = new int[5];
oneD[0] = 7;
// ...
System.out.println(oneD);
The output is an address:
[I#148cc8c
However, the libs do supply the method deepToString for this purpose, so this may also suit your purposes:
System.out.println(Arrays.deepToString(array1));
If you just want to print the data contained in the int array to a log, you can use
Arrays.deepToString
which does not use any for loops.
Working Code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}};
System.out.println(Arrays.deepToString(array));
}
}
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
This is a very general approach that works in most languages. You will have to use nested loops. The outer loop accesses the rows of the array, while the inner loop accesses the elements within that row. Then, just print it out and start a new line for every row (or choose whatever format you want it to be printed in).
for (int[] arr : array1) {
for (int v : arr) {
System.out.print(" " + v);
}
System.out.println();
}
The current output would look something like:
[I#1e63e3d
...
which shows the string representation for an integer array.
You could use Arrays.toString to display the array content:
for (int[] val : array1) {
System.out.println(Arrays.toString(val));
}

How to use java.util.Arrays

I'm trying to use the java.util.Arrays class in JavaSE 6 but not sure how i would implement it? on an array that I have generated?
before the start of the class i have
import java.util.Arrays
Java Arrays
To declare an array of integers, you start with:
int[] myArray;
To instantiate an array of ten integers, you can try:
myArray = new int[10];
To set values in that array, try:
myArray[0] = 1; // arrays indices are 0 based in Java
Or at instantiation:
int[] myArray2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
To get values from the array, try:
System.out.println(myArray[0]);
To print all the values in an array, try:
// go from 0 to one less than the array length, based on 0 indexing
for(int i = 0; i < myArray2.length; i++) {
System.out.println(myArray2[i]);
}
For more information, the tutorial from Sun/Oracle will be of great help. You can also check out the Java language specification on Arrays.
Using the Arrays Utility Class
java.util.Arrays contains a bunch of static methods. Static methods belong to the class and do not require an instance of the class in order to be called. Instead they are called with the class name as a prefix.
So you can do things like the following:
// print a string representation of an array
int[] myArray = {1, 2, 3, 4};
System.out.println(Arrays.toString(myArray));
Or
// sort a list
int[] unsorted = {3, 4, 1, 2, 5, 7, 6};
Arrays.sort(unsorted);
Well let's say you have an array
int[] myArray = new int[] { 3, 4, 6, 8, 2, 1, 9};
And you want to sort it. You do this:
// assumes you imported at the top
Arrays.sort(myArray);
Here's the whole shebang:
import java.util.Arrays;
class ArrayTest {
public static void main(String[] args) {
int[] myArray = new int[] { 3, 4, 6, 8, 2, 1, 9};
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));
}
}
And that results in
C:\Documents and Settings\glow\My Documents>java ArrayTest
[1, 2, 3, 4, 6, 8, 9]
C:\Documents and Settings\glow\My Documents>
You have not provided enough information about what you are trying to do. java.util.Arrays only exposes static methods, so you simply pass in your array and whatever other params are necessary for the particular method you are calling. For instance Arrays.fill(myarray,true) would fill a boolean array with the value true.
Here is the javadoc for java.util.Arrays
You can use a static import
import static java.util.Arrays.*;
int[] ints = {3, 4, 1, 2, 5, 7, 6};
sort(ints);
public static void main(String[] args) {
double array[] = {1.1,2.3,5.6,7.5, 12.2, 44.7,4.25, 2.12};
Arrays.sort(array,1,3);
for(int i =0;i <array.length;i++){
System.out.println(array[i]);
}
}
result:
"1.1,2.3,5.6,7.5,12.2,44.7,4.25,2.12"

Categories