How to find the index of an element in an array in Java?
In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:
System.out.println(new String(list).indexOf("e"));
But in other cases of primitive data types, you'll have to iterate over it.
How to find index of int array which match specific value
Integer myArray[]= {12,23,10,22,10};
System.out.println(Arrays.asList(myArray).indexOf(23));
will solve the problem
Arrays.asList(myArray).indexOf(23)
this search about objects so we have to use object type of int
since int
is primitive type.
String myArray[]= {"12","23","10","22","10"};
Arrays.asList(myArray).indexOf("23");
In second case this will work because String
is object.
When we define a List
,We define it as List<String>
or List<Integer>
. so primitives are not use in List
. Then Arrays.asList(myArray).indexOf("23")
find index of equivalent Object.
Finding the index of the smallest element in an array (Java)
The error is self explanatory. You fail to handle the case of empty input array.
public static int indexOfSmallest(int[] array){
// add this
if (array.length == 0)
return -1;
int index = 0;
int min = array[index];
for (int i = 1; i < array.length; i++){
if (array[i] <= min){
min = array[i];
index = i;
}
}
return index;
}
If the smallest element appears multiple times, and you want to return the index of its first occurrence, change your condition to:
if (array[i] < min)
How to find array index of largest value?
public int getIndexOfLargest( int[] array )
{
if ( array == null || array.length == 0 ) return -1; // null or empty
int largest = 0;
for ( int i = 1; i < array.length; i++ )
{
if ( array[i] > array[largest] ) largest = i;
}
return largest; // position of the first largest found
}
How do find if an index of int array ends on a specific digit Java
You can use the following method getAllWithLastDigit()
. It takes an array of int
and a digit (0-9) and returns a new array containing all elements that have that specified digit as the last digit. The elements of the original array remain untouched and therefore the order is obviously preserved.
import java.util.*;
public class Application {
public static void main(String[] args) {
int[] prices = new int[]{399, 1599, 399, 50, 10, 10, 70};
System.out.println(Arrays.toString(getAllWithLastDigit(prices, 9)));
}
public static int[] getAllWithLastDigit(int[] array, int lastDigit){
if(lastDigit < 0 || lastDigit > 9) throw new IllegalArgumentException("lastDigit must be between 0 and 9!");
var lst = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
int result = array[i];
if (result % 10 == lastDigit) lst.add(result);
}
// convert array list back to integer array
return lst.stream().mapToInt(i -> i).toArray();
}
}
Expected ouput:
[399, 1599, 399]
This uses an ArrayList
to be able to dynamically add elements to the list whenever we encounter an element that has 9 as the last digit. In the end we need to convert the list back to an array as you want to return an array of integers.
What you did is just string concatenation, instead of doing this we now add the element to a list, convert that list back to an int
array and return
it. Your implementation misses the part where a new array is created and returned.
Edit
Here a version without using ArrayList
. Here we first create an array capable of holding the maximum number of results and add a result to it while increasing a counter
for each new element. Then we have to (possibly) shrink the array down so it only contains the number of elements that are actually within the array. For this we create a copy of the array with however many elements we have in our result.
import java.util.*;
public class Application {
public static void main(String[] args) {
int[] prices = new int[]{399, 1599, 399, 50, 10, 10, 70};
System.out.println(Arrays.toString(getAllWithLastDigit(prices, 9)));
}
public static int[] getAllWithLastDigit(int[] array, int lastDigit){
if(lastDigit < 0 || lastDigit > 9) throw new IllegalArgumentException("lastDigit must be between 0 and 9!");
// create an array which has the same size as the input, this way we guarantee that we have enough space for all result
int[] elements = new int[array.length];
// counter of how many elements are in the array
int counter = 0;
for (int i = 0; i < array.length; i++) {
int result = array[i];
if (result % 10 == lastDigit) elements[counter++] = array[i];
}
// now we need to create a new array which is exactly as long as we need it (if we don't have that already)
if(counter == array.length) return elements;
// Alternative: use Java API Arrays.copyOf(elements, counter)
return copyArray(array, counter);
}
public static int[] copyArray(int[] array, int newLength){
if(newLength < 0) throw new IllegalArgumentException("Length must not be < 0");
var copy = new int[newLength];
// make sure we don't go out of bounds because the new array could be longer than the old one
var until = Math.min(array.length, newLength);
// copy over all elements
for (int i = 0; i < until; i++) {
copy[i] = array[i];
}
return copy;
}
}
Get index of array element as Int
The problem isn't that it's of type Array.index
, which is a typealias for Int
, as Nonuld says. The problem is that it's an optional. You need to unwrap the optional somehow. One way is to use "if let" optional binding:
if let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController) {
print("view controller found at index \(idfx)")
} else {
print("View controller not found in array")
}
Related Topics
Explanation of Generic <T Extends Comparable<? Super T>> in Collection.Sort/ Comparable Code
Differencebetween Reader and Inputstream
How to View Jre's Source Code in Eclipse
How to Run MySQL In-Memory for Junit Test Cases
How to Clear Permgen Space Error in Tomcat
Spring Web MVC - Validate Individual Request Params
Java Converting Int to Hex and Back Again
Stream Filter of 1 List Based on Another List
How to Ignore Pkix Path Building Failed: Sun.Security.Provider.Certpath.Suncertpathbuilderexception
Enable Partial Compilation in Intellij Idea
String S = New String("Xyz"). How Many Objects Has Been Made After This Line of Code Execute
How to Convert Map to Url Query String
What Is an Instance Variable in Java
Changing Java Platform on Which Netbeans Runs
How to Use Hibernate @Any-Related Annotations
Java List Sorting: How to Keep a List Permantly Sorted Automatically Like Treemap