How to find index of int array which match specific value [duplicate] - java

This question already has answers here:
Why is indexOf failing to find the object?
(3 answers)
Closed 9 years ago.
I have
int myArray[]= {12,23,10,22,10};
So i want to get index of 23 from myArray with out iterating any loop (for ,while ...) .
I would do something like Arrays.asList(myArray).indexOf(23)
This is not work for me . I get -1 as output .
This is work with String[]
Like
String myArray[]= {"12","23","10","22","10"};
Arrays.asList(myArray).indexOf("23")
So why this is not working with int[] ? ?

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.

I concur with Ruchira, and also want to point out that the problem has to do with the fact that int is a primitive while String and Integer are actual objects. (note I would have posted this as a comment but can't until 50 reputation ;) )

If you want to convert an array of primitives to a list of boxed primitives, take advantage of Apache Commons . Once you have the list, as shown below, use the API in List to find object by index.
List<Integer> list = Arrays.asList(ArrayUtils.toObject(myArray));

You can consider keeping your array sorted and use binary subdivision to decide an index. Insert and lookup would both be O(log(n)) in this case (instead of O(1) and O(n) respectively).
If you're doing a lot of looking up you might want to use a different data structure such as a hash map, not just for performance but also because it can be easier to write around.

Related

get() from a List, but passing long as argument in Java [duplicate]

This question already has answers here:
Using a long as ArrayList index in java
(7 answers)
Closed 2 years ago.
I am trying to get an element from a list List<Class> listofitems, and I have a globale variable position of type long. I would like to perform listofitems.get(position) but it doesnt allow me to do so since get takes int as argument. If I want to keep the type of position as long, if there are any other way to do this? (any other way besides casting position to int)?
If you wanted to do this, you'd have to construct a class that holds a grouping of lists to represent your data. You can write your own access method that splits your long into smaller ints, to access the right position in your list.
See this answer: Using a long as ArrayList index in java
This is a point where memory must be consulted through the Unsafe api. Incase of list/arrays greater than Integer.MAX_VALUE here is the link. NOTE:
Write your own implementation of the list/array.
Unsafe is literally unsafe.
Such an implementation would require long indices.
Speed will abundant.
If what you have is a List<Class>, and it cannot be changed to another type, then there is nothing you can do besides convert that long to an int. There is no way to take an arbitrary List and call get with anything but an int.

How to delete similar elements from String array or ArrayList [duplicate]

This question already has answers here:
How to get unique values from array
(13 answers)
Closed 7 years ago.
I'm totally new to programming and I have String array:
String dates[] = {"01-01-1993", "19-11-1993", "01-01-1993", "03-03-2000", "03-03-2000"};
In the above array dates[0] == dates[2] and dates[3] == dates[4], I want to delete the duplicate values which IS REPEATED and I want program to produce result like this:
dates[] = {"01-01-1993", "19-11-1993", "03-03-2000"}
Some are using ArrayList concept some are using complex for loops and I'm confused, so could you please help in achieving the above task.
Thanks In Advance.
You can use a Set to remove duplicates.
Set<T> dateSet = new HashSet<T>(Arrays.asList(dates));
dateSet will only contain unique values.
If you need to get back to an array
dates = dateSet.toArray(new String[dateSet.size()]);
Your question raises a few points:
In general, this kind of manipulation of collections is much easier and cleaner if you use the Collection classes (Set, List, etc). For example, a Set guarantees uniqueness of the elements:
String dates[] = {"01-01-1993", "19-11-1993","01-01-1993","03-03-2000","03-03-2000"};
Set<String> uniqueDates = new HashSet<>(Arrays.asList(dates));
But HashSet is unordered; if you iterate over uniqueDates the order in which you get the back is arbitrary. If the order is important, you could use LinkedHashSet:
Set<String> orderedUniqueDates = new LinkedHashSet<>(Arrays.asList(dates));
The basic collection that come with Java are pretty good; but if you use Google's Guava library (https://github.com/google/guava), it gets really nice and you can do really powerful things like finding intersections of sets, set differences etc.:
Set<String> uniqueDates = Sets.newHashSet(dates);
More fundamentally, String is a very poor choice of data type to represent Dates. Consider using either java.util.Date or (if using a Java version prior to 8) org.joda.time.DateTime (http://www.joda.org/joda-time/). Not only will this give you type safety and ensure that your data is really all dates, but you could then do things like sorting.
Using Java 8 you can do the following:
String dates[] = {"01-01-1993", "19-11-1993", "01-01-1993", "03-03-2000", "03-03-2000"};
dates = Arrays.stream(dates).distinct().toArray(String[]::new);
this will work simply
Set<T> tempSet= new HashSet<T>(Arrays.asList(dates));
String[] dates= tempSet.toArray(new String[tempSet.size()]);//copy distinct values

Groovy how to push value to array of type long

New to groovy so take it easy...
I get an error that there is no push() method for an array of longs
def mylongs=[] as long[];
somebject.each{
//logic to chooose...
mylongs.push(it.thisisalong);
}
So how do I append long values properly. Using
mylongs[mylongs.size()]=it.thisisalong
yields out of index bounds exceptions
First let me address your second question, and the larger difference between Arrays and Lists in the JVM:
Arrays, and lists in Java are 0-based, meaning that the first element can be found in a[0], and the last element, in a[a.size()-1]. Element a[a.size()] exceeds the bounds of your array, and that is what your exception tells you.
In groovy you can use a.last(), if you want to pick up the last element of an array/list, in my opinion it is more readable and self-explanatory.
If you cast your mylongs into an array before populating it, then you have fixed the size of the array, and you can push no more objects into it. If your array has variable size, then you need to use a List.
List<Long> a=[]
a << 1 as long
a << 2 as long
etc
When you need to convert it back to an array, you can do this:
a as long[]
Now to the answer of the first question, the others pretty much gave you a valid answer, but in groovy style, i'd write (providing that somebject is a collection of some type):
def mylongs= somebject.collect{ it.thisisalong } as long[]
But pushing an element into an List and be done like this, in groovy style:
myLongs << 4
You cannot append values into an array, it has a fixed size.
mylongs = someobject*.thisisalong as long[]
should do. *. is spread operator in groovy.
I ended up doing this.
def mylongs=[];
somebject.each{
//logic to chooose...
mylongs.add(it.thisisalong as long);
}

Is there a method in Java that lets you find the index of an element in an int array? [duplicate]

This question already has answers here:
Where is Java's Array indexOf?
(13 answers)
Closed 9 years ago.
I need to assess the last int in an array where a certain conditional is met. My program can work out what that int is, but it needs to also know where it's position was in the array. I searched on stack-exchange and someone posted this:
Arrays.asList(array).indexOf(indexPos);
As a possible solution, but I am not sure if I am doing it right, because I get the error
cannot find symbol. I also allowed:
int test = Arrays.asList(array).indexOf(indexPos);
And then tried to print test, but I could not even get to that point. Thanks.
You may need to import java.util.Arrays to get the symbol.
There is no guaranteed way of finding the position of an element in an array except for looping over the array - that is basically what your asList snippets are doing.
This will work as long as your arrays don't have duplicate values. If you need to handle duplicate values, you may need to rethink you data structs.
Someone posted a similar question that someone else asked. It seems that this has worked for me.
The Code is:
java.util.Arrays.asList(seq).indexOf(indexPos);
and the Question:Where is Java's Array indexOf?
Yes you have the method defined in List interface. So you need to use asList() function followed by indexOf() function.
If the array is not sorted you can use java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search function(improves performance) java.util.Arrays.binarySearch(theArray, o)
As for the error make sure you have imported java.util.Arrays. Also that you have defined Array seq and int indexPos which makes your code int test = Arrays.asList(seq).indexOf(indexPos);.

Comparing any of these value from an array Efficiently

I am having an Array of String of 10 elements.
Now I need to compare my value available in any of these Arrays value.
1 Option I thought of sorting the array and then binary search on the
same
But further analysis, I found the value needed to be compare is not exactly same, it contains some value , but even in that case, it should be successful.
Like Value to compare ,
String str = "Author"
String[] arrays = {"#Author","#Auth",#Au...}
str.contains(arrays..) actually but how to do the same .
you could use Dynamic Programming:
http://www.algorithmist.com/index.php/Longest_Common_Subsequence
this algorithm check the longest subsequence of string with the minimum complex
This is the algor in java:
http://introcs.cs.princeton.edu/java/96optimization/LCS.java.html
If you are only dealing with an array with only 10 elements... you don't need to worry about efficiency!
You can simply loop through the entire array, or instead of using a String[] use an List<string> and use the contains method.

Categories